我有以下代码,显示时间
$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');
手册:
天:如果DateTime :: diff()创建了DateInterval对象,则这是开始日期和结束日期之间的总天数。否则,几天将是错误的。
请注意,假设所有天数为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');
N.B。我使用了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("Y-m-d H:i:s")) - strtotime($endTime->format("Y-m-d H:i:s")))/3600, 1);
echo $differenceInHours;