get php DateInterval in total 'minutes'

前端 未结 5 525
鱼传尺愫
鱼传尺愫 2020-12-15 03:21

I am trying to get the PHP \"DateInterval\" value in \"total minutes\" value. How to get it? Seems like simple format(\"%i minutes\") not working?

Here is the sampl

相关标签:
5条回答
  • 2020-12-15 03:46

    If you are stuck in a position where all you have is the DateInterval, and you (like me) discover that there seems to be no way to get the total minutes, seconds or whatever of the interval, the solution is to create a DateTime at zero time, add the interval to it, and then get the resulting timestamp:

    $timeInterval      = //the DateInterval you have;
    $intervalInSeconds = (new DateTime())->setTimeStamp(0)->add($timeInterval)->getTimeStamp();
    $intervalInMinutes = $intervalInSeconds/60; // and so on
    
    0 讨论(0)
  • 2020-12-15 03:54

    I wrote two functions that just calculates the totalTime from a DateInterval. Accuracy can be increased by considering years and months.

    function getTotalMinutes(DateInterval $int){
        return ($int->d * 24 * 60) + ($int->h * 60) + $int->i;
    }
    
    function getTotalHours(DateInterval $int){
        return ($int->d * 24) + $int->h + $int->i / 60;
    }
    
    0 讨论(0)
  • 2020-12-15 04:00

    Here is the excepted answer as a method in PHP7.2 style:

    /**
     * @param \DateTime $a
     * @param \DateTime $b
     * @return int
     */
    public static function getMinutesDifference(\DateTime $a, \DateTime $b): int
    {
        return abs($a->getTimestamp() - $b->getTimestamp()) / 60;
    }
    
    0 讨论(0)
  • 2020-12-15 04:02

    That works perfectly.

    function calculateMinutes(DateInterval $int){
        $days = $int->format('%a');
        return ($days * 24 * 60) + ($int->h * 60) + $int->i;
    }
    
    0 讨论(0)
  • 2020-12-15 04:09
    abs((new \DateTime("48 hours"))->getTimestamp() - (new \DateTime)->getTimestamp()) / 60
    

    That's the easiest way to get the difference in minutes between two DateTime instances.

    0 讨论(0)
提交回复
热议问题