php 使用 strtotime() 计算时差(以小时和分钟为单位)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13741507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:59:07  来源:igfitidea点击:

Calculating the time difference(in hours and minutes) using strtotime()

phpdatedatetime

提问by Christopher

$time1 = strtotime('23:56');
$time2 = strtotime('00:21');
echo ($time1 - $time2)/60;

The expected o/p is 25.But it returns 1415;

预期的 o/p 是25. 但它返回1415;

If I change

如果我改变

$time2= strtotime('24:21');

$time2= strtotime('24:21');

It returns -25which is partially correct(since it returns negative ).

它返回 -25这是部分正确的(因为它返回负数)。

Can any one suggest me, some other function to calculate time difference in minutes.

任何人都可以建议我使用其他一些函数来计算以分钟为单位的时间差。

Thanks :)

谢谢 :)

回答by gries

if you use strtotime with only a time it takes the current date so:

如果您仅使用 strtotime 的时间,则它需要当前日期,因此:

$time1 = strtotime('23:56');  // 2012-12-06 23:56
$time2 = strtotime('00:21');  // 2012-12-06 00:21
echo ($time1 - $time2)/60;

回答by Rawkode

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

这是因为您没有指定日期,所以 00:21 是今天的开始,23:56 是今天的结束

1415 being the 23 hours difference.

1415 是 23 小时的差异。

回答by Salman A

Assume that $time2must be greater than or equal to $time1. Then adjust $time2accordingly:

假设$time2必须大于或等于$time1。然后相应地调整$time2

Example 1 -- same day

示例 1 -- 同一天

$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

示例 2 -- 日期滚动

$time1 = strtotime('23:56');
$time2 = strtotime('00:21');
if($time2 < $time1) {
    $time2 += 24 * 60 * 60;
}
echo ($time2 - $time1) / 60; // 25

回答by pbhd

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...

php的回答是正确的,它怎么知道你在想第二天呢?只需从 1440(一天中的分钟数)中减去您的值,您就会得到想要的结果...

回答by ma?ek

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

预期的输出不是25。您是从一天的较晚时间减去一天的较早时间。晚上 11:56 - 上午 12:21 几乎是 24 小时(或 1440 分钟)。

Your result is 1415which is exactly what's expected.

您的结果1415正是预期的结果。

回答by vaibhav

You can save the timestamp of $tempand use date function

您可以保存时间戳$temp并使用日期功能

 $time1 = timestamp;
$time2 = timestamp;
$temp  = $time1 - $time2;

echo date("F j Y i:s",$temp);