php date_diff in hours

匿名 (未验证) 提交于 2019-12-03 02:41:02

问题:

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 />"; 

How can I get the hours:minutes:seconds elapsed? I'm trying to stay with the date_diff function.

回答1:

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.

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

As for DateDiff::format, the doc says...

The DateInterval::format() method does not recalculate carry over points in time strings nor in date segments.



回答2:

The DateInterval object, returned by date_diff stores each period of time separately, seconds, minutes, hours, days, months and years.

Since the difference is 2 days, the hours property is 0, which is what you get.



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