user2894688
user2894688

Reputation: 31

PHP < 5.3 => Difference in hours between two dates

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.

Upvotes: 0

Views: 160

Answers (3)

Gergo Erdosi
Gergo Erdosi

Reputation: 42048

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);

Upvotes: 1

Anthony Scaife
Anthony Scaife

Reputation: 564

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;

Upvotes: 0

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

Try this

echo round((strtotime($date1) - strtotime($date2))/(60*60));

Upvotes: 0

Related Questions