Convert DateInterval object to seconds in php

情到浓时终转凉″ 提交于 2019-12-03 01:44:18

There is a function format for this. But it wont return the number of seconds. To get number of seconds you use this technique

$seconds = abs($datetime1->getTimestamp()-$datetime2->getTimestamp());

If you really want to use $interval you need to calculate it.

$seconds = $interval->days*86400 + $interval->h*3600 
           + $interval->i*60 + $interval->s;

Here

  • 86400 is the number of seconds in a day
  • 3600 is the number of seconds in an hour
  • 60 is the number of seconds in a minute
Brilliand

Another way to get the number of seconds in an interval is to add it to the zero date, and get the timestamp of that date:

$seconds = date_create('@0')->add($interval)->getTimestamp();

This method will handle intervals created via the DateInterval contructor more or less correctly, whereas shiplu's answer will ignore years, months and days for such intervals. However, shiplu's answer is more accurate for intervals that were created by subtracting two dates. For intervals consisting only of hours, minutes and seconds, both methods will get the correct answer.

I would only add to shiplu's answer:

function dateIntervalToSeconds($interval)
{
    $seconds = $interval->days*86400 + $interval->h*3600 
       + $interval->i*60 + $interval->s;
    return $interval->invert == 1 ? $seconds*(-1) : $seconds;
}

To handle negative intervals.

Note that - contrary to Brilliand's answer - The code above will consider correctly years, months and dates. Because $interval->days is an absolute value ($interval->d is relative to the month).

EDIT: this function is still not correct, as pointed out by @Brilliand. A counter-example is

new DateInterval('P4M3DT2H'); 

It doesn't handle months well.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!