问题
$time1 = strtotime('23:56');
$time2 = strtotime('00:21');
echo ($time1 - $time2)/60;
The expected o/p is 25.But it returns 1415;
If I change
$time2= strtotime('24:21');
It returns -25 which is partially correct(since it returns negative ).
Can any one suggest me, some other function to calculate time difference in minutes.
Thanks :)
回答1:
if you use strtotime with only a time it takes the current date so:
$time1 = strtotime('23:56'); // 2012-12-06 23:56
$time2 = strtotime('00:21'); // 2012-12-06 00:21
echo ($time1 - $time2)/60;
回答2:
This is because you are not specifying a day, so 00:21 is the start of today and 23:56 is the end of today
1415 being the 23 hours difference.
回答3:
Assume that $time2 must be greater than or equal to $time1. Then adjust $time2 accordingly:
Example 1 -- same day
$time1 = strtotime('00:21');
$time2 = strtotime('23:56');
if($time2 < $time1) {
$time2 += 24 * 60 * 60;
}
echo ($time2 - $time1) / 60; // 1415
Example 2 -- day rolls over
$time1 = strtotime('23:56');
$time2 = strtotime('00:21');
if($time2 < $time1) {
$time2 += 24 * 60 * 60;
}
echo ($time2 - $time1) / 60; // 25
回答4:
php's answer is correct, how should it know that you think about the next day? Just subtract your value from 1440 (Minutes in a day), then you'll have the desired result...
回答5:
The expected output is not 25. You're subtracting an early time of day from a late time of day. 11:56 PM - 12:21 AM is almost 24 hours (or 1440 minutes).
Your result is 1415 which is exactly what's expected.
回答6:
You can save the timestamp of $temp and use date function
$time1 = timestamp;
$time2 = timestamp;
$temp = $time1 - $time2;
echo date("F j Y i:s",$temp);
来源:https://stackoverflow.com/questions/13741507/calculating-the-time-differencein-hours-and-minutes-using-strtotime