获得 php DateInterval 总“分钟”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16776061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get php DateInterval in total 'minutes'
提问by Rana
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?
我试图在“总分钟数”值中获取 PHP“DateInterval”值。如何获得?似乎简单的格式(“%i 分钟”)不起作用?
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:
它显示 2 天作为输出,这完全没问题。如果要在“总分钟数”中获得值,我想得到什么,所以我尝试了:
echo $interval->format('%i total minutes');
Which is not working. Any help appreciated to get my desired output.
哪个不起作用。感谢任何帮助以获得我想要的输出。
回答by deceze
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.
这是获得两个DateTime
实例之间的分钟差异的最简单方法。
回答by Neil Townsend
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:
如果您被困在只有 的位置DateInterval
,并且您(像我一样)发现似乎无法获得总分钟数、秒数或任何时间间隔,解决方案是在零处创建 DateTime时间,将间隔添加到它,然后得到结果时间戳:
$timeInterval = //the DateInterval you have;
$intervalInSeconds = (new DateTime())->setTimeStamp(0)->add($timeInterval)->getTimeStamp();
$intervalInMinutes = $intervalInSeconds/60; // and so on
回答by Genmais
I wrote two functions that just calculates the totalTime from a DateInterval. Accuracy can be increased by considering years and months.
我写了两个函数,它们只是从 DateInterval 计算 totalTime。可以通过考虑年和月来提高精度。
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;
}
回答by ggallego
That works perfectly.
这完美地工作。
function calculateMinutes(DateInterval $int){
$days = $int->format('%a');
return ($days * 24 * 60) + ($int->h * 60) + $int->i;
}
回答by Sebastian Viereck
Here is the excepted answer as a method in PHP7.2 style:
这是作为 PHP7.2 样式方法的例外答案:
/**
* @param \DateTime $a
* @param \DateTime $b
* @return int
*/
public static function getMinutesDifference(\DateTime $a, \DateTime $b): int
{
return abs($a->getTimestamp() - $b->getTimestamp()) / 60;
}