显示PHP时间大于24小时,如70小时

我有下面的代码显示时间

$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小时一样显示真正的小时差异!

谢谢,

解决方法:

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

$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');

注:由于manual中的注释,我使用了格式(‘U’)而不是getTimestamp().

也不是说post-epoch和pre-negative-epoch日期需要64位!

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...