首页 文章

计算PHP DateInterval中的总秒数

提问于
浏览
76

计算两个日期之间总秒数的最佳方法是什么?到目前为止,我已尝试过以下方面:

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

但是我真的不满意使用这种半成品解决方案 .

5 回答

  • 169

    你不能比较time stamps吗?

    $now = new DateTime('now');
    $diff = $date->getTimestamp() - $now->getTimestamp()
    
  • -6

    此函数允许您从DateInterval对象获取总持续时间(以秒为单位)

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

    你可以这样做:

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

    time()返回自纪元时间(1970-01-01T00:00:00)以来的当前时间(秒),并且strtotime执行相同的操作,但是基于您给出的特定日期/时间 .

  • 5
    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;
    }
    
  • 2

    您可以输入硬数字(而不是60 * 60 - 放入3600),因此每次都不需要计算它们 .

    编辑 - 根据您的评论修复该号码 .

相关问题