2009-10-05 203 views

回答

55

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

$diff = strtotime('2009-10-05 18:11:08') - strtotime('2009-10-05 18:07:13') 
+0

注意:请确保使用大写“H”几小时(24小时模式),当你的“较低”时间是“现在”,并且你使用'date()'得到现在的日期时间('date(“Ymd H:i:s”)')。 – 2015-11-15 19:38:55

2
strtotime("2009-10-05 18:11:08") - strtotime("2009-10-05 18:07:13") 
7

PHP日期时间基准是这样的事情有所帮助:PHP Date Time Functions

strtotime()可能是最好的办法。

$seconds = strtotime('2009-10-05 18:11:08') - strtotime('2009-10-05 18:07:13') 
107

随着datetime对象,你可以做这样的:

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

$diffInSeconds = $date2->getTimestamp() - $date->getTimestamp(); 
+0

这也考虑到夏时制时间! – Brainware 2017-05-05 03:25:01

+0

这是这个问题最优雅的解决方案。这应该是被接受的答案。 – 2018-01-04 08:43:14

4

由于Unix纪元的限制,你可以有问题,1970年以前compairing日期和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; 
} 

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

  • 0数秒如果DIFF被应用到时间间隔<1个月
  • 0〜3天,如果差异是适用于时间间隔>1个月
  • 0〜14天,如果差异被应用到时间间隔> 1年

我宁愿假设某人决定审议“M”为30天,“Y”为365,收费“d”与差价“差价”走低谷非30天的月...

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

+0

使用days属性而不是d属性来获取两天之间的确切日期。所以没有不准确的结果。 – Nilz11 2016-11-27 15:16:35

相关问题