以 PHP DateInterval 计算总秒数

计算两次约会之间的总秒数的最佳方法是什么?到目前为止,我已经尝试了类似的东西:

$delta   = $date->diff(new DateTime('now'));
$seconds = $delta->days * 60 * 60 * 24;

但是,DateInterval 对象的 days属性在当前的 PHP5.3版本中似乎被破坏了(至少在 Windows 上,它总是返回相同的 6015值)。我还尝试了一种不能保留每个月(轮到30天)、闰年等天数的方法:

$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);

但我真的不喜欢使用这种半吊子的解决方案。

81591 次浏览

You could just put in the hard numbers (instead of 60*60 - put in 3600) so it doesn't need to calculate them each time.

Edit - fixed the number based off your comment.

You could do it like this:

$currentTime = time();
$timeInPast = strtotime("2009-01-01 00:00:00");


$differenceInSeconds = $currentTime - $timeInPast;

time() returns the current time in seconds since the epoch time (1970-01-01T00:00:00), and strtotime does the same, but based on a specific date/time you give.

Could you not compare the time stamps instead?

$now = new DateTime('now');
$diff = $date->getTimestamp() - $now->getTimestamp()
static function getIntervalUnits($interval, $unit)
{
// Day
$total = $interval->format('%a');
if ($unit == TimeZoneCalc::Days)
return $total;
//hour
$total = ($total * 24) + ($interval->h );
if ($unit == TimeZoneCalc::Hours)
return $total;
//min
$total = ($total * 60) + ($interval->i );
if ($unit == TimeZoneCalc::Minutes)
return $total;
//sec
$total = ($total * 60) + ($interval->s );
if ($unit == TimeZoneCalc::Seconds)
return $total;


return false;
}

This function allows you to get the total duration in seconds from a DateInterval object

/**
* @param DateInterval $dateInterval
* @return int seconds
*/
function dateIntervalToSeconds($dateInterval)
{
$reference = new DateTimeImmutable;
$endTime = $reference->add($dateInterval);


return $endTime->getTimestamp() - $reference->getTimestamp();
}

It always feels nice when what you need is already present as a class. In your case, you need a total number of seconds. Why not make a class out of that? The code could look like that:

(new TotalFullSeconds(
new IntervalFromRange(
new DateTimeFromISO8601String('2017-07-03T14:27:39+00:00'),
new DateTimeFromISO8601String('2017-07-05T14:27:39+00:00')
)
))
->value()

Besides being intuitive, you can also benefit from autocompletion facility of your IDE.

For more useful implementation, you can check out this library.

DateTime::diff returns a DateInterval object between 2 dates.

The DateInterval object gives all the informations (the number of days, hours, minutes, seconds).

Here's a sample code:

/**
* intervalToSeconds
*
* @param  DateInterval $interval
* @return int
*/
function intervalToSeconds(\DateInterval $interval) {
return $interval->days * 86400 + $interval->h * 3600 + $interval->i * 60 + $interval->s;
}


$date_1 = new \DateTime('2021-03-03 05:59:19');
$date_2 = new \DateTime('now');
$interval = $date_1->diff($date_2);
echo intervalToSeconds($interval);