将 PHP 时间显示为大于 24 小时的小时数,例如 70 小时

Show PHP time as hours greater than 24 hrs like 70 hrs

我有以下显示时间的代码

$now = date_create(date("Y-m-d H:i:s"));

$replydue = date_create($listing['replydue_time']);

$timetoreply = date_diff($replydue, $now);

echo $timetoreply->format('%H:%I')

我的问题是,如果差异超过 24 小时,它会在更多 24 小时内中断时间并显示 1 或 2 或任何时间但低于 24 小时。

我怎样才能显示像 74 小时这样的真实时差!

谢谢,

您可以使用以下代码:

<?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)";
?>

尝试按照上面的过程。如果您需要任何帮助,我很乐意提供帮助。

希望有用。

来源:How to Calculate Hours Between Two Dates in 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("Y-m-d H:i:s")) - strtotime($endTime->format("Y-m-d H:i:s")))/3600, 1);
echo $differenceInHours;

理想情况下,我更喜欢以下方法.. 而不是重新发明轮子或进行大量手动转换:

$now = new DateTime();
$replydue = new DateTime($listing['replydue_time']);

$timetoreply_hours = $timetoreply->days * 24 + $timetoreply->h;
echo $timetoreply_hours.':'.$timetoreply->format('%I');

来自manual

days: If the DateInterval object was created by DateTime::diff(), then this is the total number of days between the start and end dates. Otherwise, days will be FALSE.

请注意,这假设所有的日子都是 24 小时,在实行夏令时的地区可能并非如此

我编写了以下函数来协助完成此操作:

/**
 * @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');

N.B. 由于 manual.[= 中的评论,我使用 format('U') 而不是 getTimestamp() 18=]

post-纪元和前负纪元日期也不需要 64 位!