Home » Php » datetime – get php DateInterval in total 'minutes'

datetime – get php DateInterval in total 'minutes'

Posted by: admin April 23, 2020 Leave a comment

Questions:

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 sample code:

$test = new \DateTime("48 hours");
$interval = $test->diff(new \DateTime());

Now if I try to get the interval in total days, its fine:

echo $interval->format('%a total days');

It is showing 2 days as output, which is totally fine. What I am trying to get if to get the value in “total minutes”, so I tried:

echo $interval->format('%i total minutes');

Which is not working. Any help appreciated to get my desired output.

How to&Answers:
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.

Answer:

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

Answer:

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

Answer:

That works perfectly.

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

Answer:

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