$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位!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。