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
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;
}
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;
}
That works perfectly.
function calculateMinutes(DateInterval $int){
$days = $int->format('%a');
return ($days * 24 * 60) + ($int->h * 60) + $int->i;
}
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.