Link to home
Start Free TrialLog in
Avatar of BR
BRFlag for Türkiye

asked on

php date function ( diffrence between two dates )

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?
Avatar of Thomas

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of SniperCode Sheva
SniperCode Sheva

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

Avatar of BR


thank you SniperCode Sheva
You are welcome.
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.
Avatar of BR


Thank you Ray Paseur
You are right
Thank you very much

I will use the first answer