3

在计算 2 个不同的 unix 时间戳之间的差异后,我一直无法显示小时和分钟。假设我有这 2 个 unix 时间戳:

1) 1384327800
2) 1384300800

不同的是

27000

如果我除以 27000/3600 我得到

7.5

但我想要的是显示

7:30

或者

7 hours and 30 minutes

最好的方法是什么?

4

4 回答 4

5

你只需要做一点计算:

$diff = 27000;

$hour = floor($diff / 3600);
$min  = floor(($diff - $hour * 3600) / 60);
$sec = $diff - $hour * 3600 - $min * 60;

echo "$hour hours, $min minutes, $sec seconds";

或者尝试使用 DateTime 类:

$dt1 = new DateTime('@1384327800');
$dt2 = new DateTime('@1384300801');
$diff = $dt1->diff($dt2);
echo $diff->format('%h hours, %i minutes, %s seconds');
于 2013-11-13T21:51:32.010 回答
3

算法方式(没有任何函数/库的自动计算):

$diff_in_minutes = ($timestamp1 - $timestamp2) / 60;
$minutes = $diff_in_minutes % 60;
$hours = ($diff_in_minutes - $minutes) / 60;

$diff_string = $hours . ':' . $minutes;
于 2013-11-13T21:54:16.967 回答
2

DateTime()DateInterval::format()

$dt1 = new DateTime('@1384327800');
$dt2 = new DateTime('@1384300800');
$diff = $dt1->diff($dt2);
echo $diff->format('%h hours and %i minutes');

如果需要,最后一点将从您的字符串中删除不必要的时间段。

$elapsed = $diff->format('%y years, %m months, %a days, %h hours, %i minutes, %S seconds');
$elapsed = str_replace(array('0 years,', ' 0 months,', ' 0 days,',  ' 0 hours,', ' 0 minutes,'), '', $elapsed);
$elapsed = str_replace(array('1 years, ', ' 1 months, ', ' 1 days, ',  ' 1 hours, ', ' 1 minutes'), array('1 year, ', '1 month, ', ' 1 day, ', ' 1 hour, ', ' 1 minute'), $elapsed);
echo $elapsed;
于 2013-11-13T21:50:33.573 回答
1

对于完全按照描述的完整长格式:

date_default_timezone_set('UTC');
$timestamp1 = new DateTime('@1384327800');
$timestamp2 = new DateTime('@1384300800');
$diff = $timestamp1->diff($timestamp2);
$timemap = array('y' => 'year',
                 'm' => 'month',
                 'd' => 'day',
                 'h' => 'hour',
                 'i' => 'minute',
                 's' => 'second');
$timefmt = array();

foreach ($timemap as $prop => $desc) {
    if ($diff->$prop > 0) {
        $timefmt[] = ($diff->$prop > 1) ? "{$diff->$prop} {$desc}s" : "{$diff->$prop} $desc";
    }
}

$diffstr = (count($timefmt) > 1)
    ? $diff->format(sprintf('%s and %s',
          implode(', ', array_slice($timefmt, 0, -1)), end($timefmt)))
    : end($timefmt);
var_dump($diffstr);

这给了我以下信息:

string(22) "7 hours and 30 minutes"
于 2013-11-13T22:22:04.940 回答