获取PHP中两个日期时间之间的间隔秒?

Mis*_*ier 62 php datetime

2009-10-05 18:11:08

2009-10-05 18:07:13

这应该生成235,怎么办呢?

JCM*_*JCM 145

使用DateTime对象,您可以这样做:

$date = new DateTime( '2009-10-05 18:07:13' );
$date2 = new DateTime( '2009-10-05 18:11:08' );

$diffInSeconds = $date2->getTimestamp() - $date->getTimestamp();
Run Code Online (Sandbox Code Playgroud)

  • 这是该问题最优雅的解决方案.这应该是公认的答案. (5认同)

Pau*_*xon 91

你可以使用strtotime()来做到这一点:

$diff = strtotime('2009-10-05 18:11:08') - strtotime('2009-10-05 18:07:13')
Run Code Online (Sandbox Code Playgroud)

DateTime对象可以采用类似的方法,例如

$date = new DateTime( '2009-10-05 18:07:13' );
$date2 = new DateTime( '2009-10-05 18:11:08' );

$diff = $date2->getTimestamp() - $date->getTimestamp();
Run Code Online (Sandbox Code Playgroud)


And*_*rew 8

PHP Date Time reference对以下内容很有帮助:PHP Date Time Functions

strtotime()可能是最好的方法.

$seconds = strtotime('2009-10-05 18:11:08') - strtotime('2009-10-05 18:07:13')
Run Code Online (Sandbox Code Playgroud)


des*_*ise 7

对于那些担心使用时间戳的局限性(即使用 1970 年之前和 2038 年之后的日期)的人,您可以像这样简单地计算以秒为单位的差异:

$start = new DateTime('2009-10-05 18:11:08');
$end = new DateTime('2009-10-05 18:07:13');
$diff = $end->diff($start);

$daysInSecs = $diff->format('%r%a') * 24 * 60 * 60;
$hoursInSecs = $diff->h * 60 * 60;
$minsInSecs = $diff->i * 60;

$seconds = $daysInSecs + $hoursInSecs + $minsInSecs + $diff->s;

echo $seconds; // output: 235
Run Code Online (Sandbox Code Playgroud)

为那些有兴趣阅读更多内容的人写了一篇博文


小智 5

由于 Unix 纪元的限制,比较 1970 年之前和 2038 年之后的日期可能会出现问题。我选择放宽精度(=不看一秒)但避免通过 Unix 纪元转换 (getTimestamp)。这取决于你在做什么...

就我而言,使用 365 (12*30) 和“30”作为平均月长,减少了可用输出中的错误。

function DateIntervalToSec($start,$end){ // as datetime object returns difference in seconds
    $diff = $end->diff($start);
    $diff_sec = $diff->format('%r').( // prepend the sign - if negative, change it to R if you want the +, too
                ($diff->s)+ // seconds (no errors)
                (60*($diff->i))+ // minutes (no errors)
                (60*60*($diff->h))+ // hours (no errors)
                (24*60*60*($diff->d))+ // days (no errors)
                (30*24*60*60*($diff->m))+ // months (???)
                (365*24*60*60*($diff->y)) // years (???)
                );
    return $diff_sec;
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果“平均”数量用于差异,则错误可能为 0。PHP 文档没有谈到这个......在糟糕的情况下,错误可能是:

  • 如果 diff 应用于时间间隔 < 1 个月,则为 0 秒
  • 如果将差异应用于时间间隔 > 1 个月,则为 0 到 3 天
  • 如果将差异应用于时间间隔 > 1 年,则为 0 到 14 天

我更愿意假设有人决定将“m”视为 30 天,将“y”视为 365 天,当“diff”走过非 30 天的月份时,向“d”收取差异...

如果有人对此有更多了解并可以提供官方文档,欢迎!