get difference in time in HH:MM format php

半世苍凉 提交于 2019-11-30 09:14:54

问题


how can i get this to output

HH:MM format?

 $to_time = strtotime("2008-12-13 10:42:00");  <--AM
 $from_time = strtotime("2008-12-14 8:21:00");  <-- PM
 $stat = round(abs($to_time - $from_time) / 60,2). "min";

what i got from this is 1299 mins

but i cant figure out how to make it output

21h:41m


回答1:


Firstly, 8:21:00 will be interpreted as 8AM unless you specified otherwise using DateTime::createFromFormat().

To work out time differences, use DateTime::diff():

$to = new DateTime("2008-12-13 10:42:00");
$from = new DateTime("2008-12-14 8:21:00");

$stat = $to->diff($from); // DateInterval object

echo $stat->format('%Hh:%Im');

This will display the hour/minute difference between the two times, but only up to 24 hours.

If you need more than 24 hours, you should do the following:

$hours   = $stat->days * 24 + $stat->h;
$minutes = $stat->i;

printf('%02sh:%sm', $hours, $minutes);



回答2:


First of all you need to include AM and PM in your date strings, otherwise 2008-12-14 8:21:00 will be interpreted as 8:21 AM

Now the difference between two dates is 2019 that is 33h:19m, you cant' have t with standard date formats, since they support only 24h clock. You should keep $stat as integer, and display it with sprintf like like this:

echo sprintf('%02dh:%02dm', $stat/60, $stat%60);


来源:https://stackoverflow.com/questions/13002723/get-difference-in-time-in-hhmm-format-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!