gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:32:42 24 4
gpt4 key购买 nike

我有下面显示时间的代码

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

N.B. 由于 manual 中的注释,我使用了 format('U') 而不是 getTimestamp() .

另外,后纪元和负纪元前的日期也不需要 64 位!

关于php - 将 PHP 时间显示为大于 24 小时的小时数,例如 70 小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30073976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com