简体   繁体   中英

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.

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

尝试这个

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM