php date_diff in hours

前端 未结 2 1377
执笔经年
执笔经年 2021-01-28 09:47

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         


        
2条回答
  •  北恋
    北恋 (楼主)
    2021-01-28 10:28

    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.

提交回复
热议问题