Php 日期时间算法

Php 日期时间算法,php,datetime,Php,Datetime,我有点被PHP的DateInterval类卡住了。我真正想要的是两个DateTime戳记之间经过的秒数 $t1 = new DateTime( "20100101T1200" ); $t2 = new DateTime( "20100101T1201" ); // number of seconds between t1 and t2 should be 60 echo "difference in seconds: ".$t1->diff($t2)->format("%s");

我有点被PHP的
DateInterval
类卡住了。我真正想要的是两个
DateTime
戳记之间经过的秒数

$t1 = new DateTime( "20100101T1200" );
$t2 = new DateTime( "20100101T1201" );
// number of seconds between t1 and t2 should be 60

echo "difference in seconds: ".$t1->diff($t2)->format("%s");

然而我得到的只是零。
DateInterval
类是否不适合算术?如何获得两个时间戳之间的“精确”秒数(或小时数,或其他任何数字?

如果您只想快速获得秒数,不妨使用

$diff = abs($t1->getTimestamp() - $t2->getTimestamp());

代码返回0,因为实际的差为0,所以示例中的差为1分钟(1分钟,0秒)。如果您打印%i格式,您将得到1,这是
$t1
$t2

的正确差值。我想看看您如何获得天数以上的确切数字。谢谢!我对类型安全的
DateInterval
非常满意:您只能将它添加到
DateTime
,这太棒了。但这确实奏效了。(在PHP5.2上,您可以使用
DateTime::format(“U”)
来检索自纪元以来的秒数)很高兴能提供帮助,我也很高兴看到人们在生产中使用PHP5.3:)