php date function ( diffrence between two dates )

BR used Ask the Experts™
Dear Experts,

I'd like to find the time duration in days and months between two dates.

I have two dates

echo $today = date('Y-m-d');
echo "<br>";
echo $seconddate =  "2017-10-18";
echo "<br>";
echo $diffrence = ($seconddate - $today);

Open in new window

but it doesn't work. what should I do?
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

If you cast both dates to a DateTime, you can use the Diff method to calculate the difference between 2 dates.
Hello, try this:

$date1 = "now";
$date2 = "2017-10-18";

$diff = abs(strtotime($date2) - strtotime($date1));

$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));

printf("%d years, %d months, %d days\n", $years, $months, $days);

Open in new window

BRDigital Marketing


thank you SniperCode Sheva
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

You are welcome.
Most Valuable Expert 2011
Top Expert 2016

The correct answer here is the first comment from Thomas.  It's an anti-practice to write your own date/time arithmetic, especially because it will often be wrong in months that do not have 30 days, in leap years, or across daylight savings time.  Instead use the built-in PHP functionality.

You can learn more about the ways we handle date/time values in this article.

You can get better answers here at E-E if you search the articles first, and if you leave your questions open a bit longer.  I would recommend leaving your questions open for at least 24 hours.

I do not recommend using the accepted solution in a deployed application.
BRDigital Marketing


Thank you Ray Paseur
You are right
Thank you very much

I will use the first answer

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial