简体   繁体   中英

PHP DateTime: How to get “diff” between two times using 24 hour clock format

Trying to subtract two times:

$obtime = "2310";
$runtime = "0048";

$run=new DateTime($runtime);
$ob=new DateTime($obtime);
$interval= $run->diff($ob);
$age=$interval->format('%H%I');
print "Age is: $age\n";

The above will output 2222, meaning 22 hours and 22 minutes difference. Of course, we know that clocks go forward, and 0048 is only 1 hour 38 min after 2310.

Is there a better way to find the time difference between two "24hr" times?

how about

$obtime = strtotime("2310");
$runtime = strtotime("0048");
echo gmdate("H:i:s", $obtime - $runtime);

Thanks gwillie. That did not work as you have it, but, it's because of the order of the time variables.

If you subtract the OLDER time from the NEWER time, it works.

This outputs 1 hr 38 min:

$obtime = strtotime("2210");
$runtime = strtotime("2348");
echo gmdate("H:i", $runtime - $obtime);

While this outputs 22 hr 22min:

$obtime = strtotime("2210");
$runtime = strtotime("2348");
echo gmdate("H:i", $obtime - $runtime);

Good to know that this method can go forward or backward, while the original method I was using is not that "smart".

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