Convert DateInterval object to seconds in php

后端 未结 3 1087
时光取名叫无心
时光取名叫无心 2021-02-05 08:23
$datetime1 = date_create(\'2009-10-11\');
$datetime2 = date_create(\'2009-10-13\');
$interval = date_diff($datetime1, $datetime2);

How do i convert the

3条回答
  •  天涯浪人
    2021-02-05 09:11

    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.

提交回复
热议问题