计算PHP DateInterval中的总秒数 [英] Calculate total seconds in PHP DateInterval
问题描述
计算两个日期之间的总秒数的最佳方式是什么?到目前为止,我已经尝试过以下一些方面:
What is the best way to calculate the total number of seconds between two dates? So far, I've tried something along the lines of:
$delta = $date->diff(new DateTime('now'));
$seconds = $delta->days * 60 * 60 * 24;
但是,DateInterval的 days
对象似乎在目前的PHP5.3构建中被破坏(至少在Windows上,它总是返回相同的 6015
值)。我也试图以这样一种方式去做,这样一来,每个月都不会保留天数(回合到30),闰年等:
However, the days
property of the DateInterval object seems to be broken in the current PHP5.3 build (at least on Windows, it always returns the same 6015
value). I also attempted to do it in a way which would fail to preserve number of days in each month (rounds to 30), leap years, etc:
$seconds = ($delta->s)
+ ($delta->i * 60)
+ ($delta->h * 60 * 60)
+ ($delta->d * 60 * 60 * 24)
+ ($delta->m * 60 * 60 * 24 * 30)
+ ($delta->y * 60 * 60 * 24 * 365);
但是,对于使用这个半分解决方案我真的不高兴。
But I'm really not happy with using this half-assed solution.
推荐答案
你可以不比较,而不是.gettimestamp.phprel =noreferrer>时间戳
Could you not compare the time stamps instead?
$now = new DateTime('now');
$diff = $date->getTimestamp() - $now->getTimestamp()
这篇关于计算PHP DateInterval中的总秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!