Показывать время PHP как часы более 24 часов, например, 70 часов

У меня есть код, который показывает время

$now = date_create(date("Ymd H:i:s")); $replydue = date_create($listing['replydue_time']); $timetoreply = date_diff($replydue, $now); echo $timetoreply->format('%H:%I') 

Byt моя проблема заключается в том, что разница составляет более 24 часов, она прерывает время более 24 часов и показывает 1 или 2 или любые часы, но ниже 24 часов.

Как я могу показать реальную часовую разницу, как 74 часа!

Благодаря,

В идеале я бы предпочел следующий подход: вместо того, чтобы изобретать колесо или делать много ручных преобразований:

 $now = new DateTime(); $replydue = new DateTime($listing['replydue_time']); $timetoreply_hours = $timetoreply->days * 24 + $timetoreply->h; echo $timetoreply_hours.':'.$timetoreply->format('%I'); 

Из руководства :

days: если объект DateInterval был создан DateTime :: diff (), то это общее количество дней между датами начала и окончания. В противном случае, дни будут ЛОЖНЫМИ.

Обратите внимание, что это предполагает, что все дни – 24 часа, что может быть не так в областях с DST

Для этого я написал следующую функцию:

 /** * @param DateTimeInterface $a * @param DateTimeInterface $b * @param bool $absolute Should the interval be forced to be positive? * @param string $cap The greatest time unit to allow * * @return DateInterval The difference as a time only interval */ function time_diff(DateTimeInterface $a, DateTimeInterface $b, $absolute=false, $cap='H'){ // Get unix timestamps $b_raw = intval($b->format("U")); $a_raw = intval($a->format("U")); // Initial Interval properties $h = 0; $m = 0; $invert = 0; // Is interval negative? if(!$absolute && $b_raw<$a_raw){ $invert = 1; } // Working diff, reduced as larger time units are calculated $working = abs($b_raw-$a_raw); // If capped at hours, calc and remove hours, cap at minutes if($cap == 'H') { $h = intval($working/3600); $working -= $h * 3600; $cap = 'M'; } // If capped at minutes, calc and remove minutes if($cap == 'M') { $m = intval($working/60); $working -= $m * 60; } // Seconds remain $s = $working; // Build interval and invert if necessary $interval = new DateInterval('PT'.$h.'H'.$m.'M'.$s.'S'); $interval->invert=$invert; return $interval; } 

Это можно использовать:

 $timetoreply = time_diff($replydue, $now); echo $timetoreply->format('%r%H:%I'); 

NB Я использовал format('U') вместо getTimestamp() из-за комментария в руководстве .

Также не для того, чтобы 64-бит был необходим для дат после эпохи и до отрицательных эпох!

Вы можете использовать код ниже:

 <?php $date1 = "2014-05-27 01:00:00"; $date2 = "2014-05-28 02:00:00"; $timestamp1 = strtotime($date1); $timestamp2 = strtotime($date2); echo "Difference between two dates is " . $hour = abs($timestamp2 - $timestamp1)/(60*60) . " hour(s)"; ?> 

Попробуйте выполнить описанный выше процесс. Если вам нужна помощь, я буду рад помочь.

Надеюсь, он сработает.

Как рассчитать часы между двумя датами в PHP

Я предлагаю это одно решение, если вам это нравится в часах:

 echo $interval->format('%a')*24+$interval->format('%h'); 

в отношении примечания ниже – это может быть и так:

 echo $interval->days*24 + $interval->h; 

В приведенном ниже коде будет отображаться разница в часах между любыми двумя днями. В этом случае, 72. Надеюсь, это поможет!

 <?php $startTime = new \DateTime('now'); $endTime = new \DateTime('+3 day'); $differenceInHours = round((strtotime($startTime->format("Ymd H:i:s")) - strtotime($endTime->format("Ymd H:i:s")))/3600, 1); echo $differenceInHours;