0

In a current project I have hit a wall because I need to compare two dates and find the difference between the dates (in hours), this would be easy if the server was >= 5.3, can someone help me?

I have the difference in timestamp

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

but I don't know what to do next...

Thank you.

  • Please check this out http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php?rq=1 It explains the old way (`strtotime`) and new way (`DateTime`) – cornelb Jul 18 '14 at 10:36

3 Answers3

1

In your code $diff is the difference in seconds. You can convert the seconds to hours like this:

$hours = floor($diff / (60 * 60));

Edit: To get minutes and seconds:

$minutes = floor(($diff - $hours * 60 * 60) / 60);
$seconds = floor($diff - $hours * 60 * 60 - $minutes * 60);
Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
0

Try this

echo round((strtotime($date1) - strtotime($date2))/(60*60));
웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91
  • Thank you! This works perfectly, now I just need to find out how to show this as H:m:s (like 36hours:27minutes:12seconds), is this possible? – user2894688 Jul 18 '14 at 10:40
0

In your code $diff is in seconds. There are 3600 seconds in an hour, so:

$date1 = "2014-07-15";
$date2 = "2014-07-17";

$diff_seconds = abs(strtotime($date1)-strtotime($date2));
$diff_hours = $diff_seconds/3600;

echo $diff_seconds.' '.$diff_hours;
Anthony Scaife
  • 564
  • 5
  • 15