php date_diff以小时为单位 [英] php date_diff in hours
问题描述
如何使代码下面的转换天数小时?
How is it possible to make the code below convert days in hours?
$timestart = date_create('02/11/2011' . $row->timestart); //$row->timestart returns time in 00:00:00 format
$timestop = date_create('02/11/2011' . $row->timestop); //$row->timestop returns time in 00:00:00 format
date_add($timestop, date_interval_create_from_date_string('2 days')); //add 2 days
$date_diff = date_diff($timestart, $timestop);
echo "Timespan: ";
echo $date_diff->format('%h hours');
echo "<br />";
如何获取小时:分钟:秒
已经过去了我正在努力留下 date_diff
函数。
How can I get the hours:minutes:seconds
elapsed? I'm trying to stay with the date_diff
function.
推荐答案
date_diff()的结果是 DateInterval 类的对象。这样的对象具有非常有用的属性 - $ days
:它是开始和结束日期之间的总天数。此外,它存储(作为其公共属性)小时,分钟和秒的差异。
The result of date_diff() is an object of DateInterval class. Such object has a very useful property - $days
: it's total number of days between the starting and the ending dates. Besides, it stores (as its public properties) the difference in hours, minutes and seconds.
所以,我想,你需要的只是提取这些属性的值$ date_diff变量,然后将 24 * $ days
添加到小时数。 )所有这些都可以包装成一个简单的函数:
So, I suppose, what you need is just extract values of these properties from $date_diff variable, then add 24*$days
to the hours number. ) All this can be wrapped into a simple function:
function hms_date_diff(DateInterval $date_diff) {
$total_days = $date_diff->days;
$hours = $date_diff->h;
if ($total_days !== FALSE) {
$hours += 24 * $total_days;
}
$minutes = $date_diff->i;
$seconds = $date_diff->s;
return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}
对于DateDiff :: format, doc 说...
As for DateDiff::format, the doc says...
DateInterval :: format()方法不会重新计算在时间字符串或日期段中的
点。
The DateInterval::format() method does not recalculate carry over points in time strings nor in date segments.
这篇关于php date_diff以小时为单位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!