php date_diff in hours

前端 未结 2 1378
执笔经年
执笔经年 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:11

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题