我有以下显示时间的代码
$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')
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果差异超过 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');
Run Code Online (Sandbox Code Playgroud)
从手册中:
days:如果 DateInterval 对象是通过 DateTime::diff() 创建的,则这是开始日期和结束日期之间的总天数。否则,days 将为 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;
}
Run Code Online (Sandbox Code Playgroud)
这可以使用:
$timetoreply = time_diff($replydue, $now);
echo $timetoreply->format('%r%H:%I');
Run Code Online (Sandbox Code Playgroud)
注意,由于手册中的注释,我已使用format('U')代替。getTimestamp()
另外,纪元后和负纪元前的日期也不需要 64 位!
| 归档时间: |
|
| 查看次数: |
6682 次 |
| 最近记录: |