get php DateInterval in total 'minutes'

久未见 提交于 2019-11-29 01:02:05
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.

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

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;
}

That works perfectly.

function calculateMinutes(DateInterval $int){
    $days = $int->format('%a');
    return ($days * 24 * 60) + ($int->h * 60) + $int->i;
}

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