Date Difference in php on days?

PhpDateDatediff

Php Problem Overview


Is there a quick way to calculate date difference in php? For example:

$date1 = '2009-11-12 12:09:08';
$date2 = '2009-12-01 08:20:11';

And then do a calculation, $date2 minus $date1

I read php.net documentation, but no luck. Is there a quick way to do it?

Php Solutions


Solution 1 - Php

I would recommend to use date->diff function, as in example below:

   $dStart = new DateTime('2012-07-26');
   $dEnd  = new DateTime('2012-08-26');
   $dDiff = $dStart->diff($dEnd);
   echo $dDiff->format('%r%a'); // use for point out relation: smaller/greater
  

see http://www.php.net/manual/en/datetime.diff.php

Solution 2 - Php

strtotime will convert your date string to a unix time stamp. (seconds since the unix epoch.

$ts1 = strtotime($date1);
$ts2 = strtotime($date2);

$seconds_diff = $ts2 - $ts1;

Solution 3 - Php

Below code will give the output for number of days, by taking out the difference between two dates..

$str = "Jul 02 2013";
$str = strtotime(date("M d Y ")) - (strtotime($str));
echo floor($str/3600/24);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmysqllearnerView Question on Stackoverflow
Solution 1 - PhpadamView Answer on Stackoverflow
Solution 2 - PhptxyojiView Answer on Stackoverflow
Solution 3 - PhpAnirudh SoodView Answer on Stackoverflow