我有下面的时间戳1347216222
,它是一天的时间戳,我将它与time_since
函数一起使用,以检查它以小时为单位的时间戳。。分钟等
<?php
/* Works out the time since the entry post, takes a an argument in unix time (seconds) */
function time_since($original) {
// array of time period chunks
$chunks = array(
array(60 * 60 * 24 * 365 , 'year'),
array(60 * 60 * 24 * 30 , 'month'),
array(60 * 60 * 24 * 7, 'week'),
array(60 * 60 * 24 , 'day'),
array(60 * 60 , 'hour'),
array(60 , 'minute'),
);
$today = time(); /* Current unix time */
$since = $today - $original;
// $j saves performing the count function each time around the loop
for ($i = 0, $j = count($chunks); $i < $j; $i++) {
$seconds = $chunks[$i][0];
$name = $chunks[$i][1];
// finding the biggest chunk (if the chunk fits, break)
if (($count = floor($since / $seconds)) != 0) {
// DEBUG print "<!-- It's $name -->'n";
break;
}
}
$print = ($count == 1) ? '1 '.$name : "$count {$name}s";
if ($i + 1 < $j) {
// now getting the second item
$seconds2 = $chunks[$i + 1][0];
$name2 = $chunks[$i + 1][1];
// add second item if it's greater than 0
if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) {
$print .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s";
}
}
return $print;
}
echo time_since(1347216222);
?>
输出为-1 years, 12 months
。有人能帮我解决这个问题吗?
我定制了使用DateTime
和DateInterval
的函数,使其可读性更强。
它与您发布的函数在处理时差方面有所不同。在您的案例中,您测试了两次值(每个"单元"一次)。这需要你进行复杂的计算。
另一方面,下面的函数利用了DateInterval
在年、月、天、小时、分钟和秒方面为您提供了现成的差异(例如,2015年和2014年之间的差异是1年和0秒,而不是UNIX时间戳)。此外,DateTime
的使用使您能够优雅地处理时区。
话虽如此,你所需要关心的就是如何打印差异,这正是for
循环的目的——我们提取两个值并使用一个额外的项目(我们称这些项目为守护者),以在我们想要提取第二个项目时保存额外的条件。
功能如下:
<?php
function pluralize($number, $unit) {
return $number . ' ' . $unit . ($number !== 1 ? 's' : '');
}
function time_since(DateTime $original) {
$now = new DateTime('now');
$diff = $now->diff($original);
//is from the past?
if ($diff->invert) {
$chunks = [
[$diff->y, 'year'],
[$diff->m, 'month'],
[$diff->d, 'day'],
[$diff->h, 'hour'],
[$diff->i, 'minute'],
[$diff->s, 'second'],
[0, 'guardian'],
];
for ($i = 0; $i < count($chunks) - 1; $i ++) {
list ($value, $unit) = $chunks[$i];
if ($value !== 0) {
$text = pluralize($value, $unit);
//append next unit as well, if it's available and nonzero
list ($nextValue, $nextUnit) = $chunks[$i + 1];
if ($nextValue !== 0) {
$text .= ' ' . pluralize($nextValue, $nextUnit);
}
return $text;
}
}
}
return 'just now';
}
测试:
echo time_since(new DateTime('2014-01-01')) . PHP_EOL;
echo time_since(new DateTime('2014-10-09')) . PHP_EOL;
echo time_since(new DateTime('2014-11-09')) . PHP_EOL;
echo time_since(new DateTime('2014-11-10')) . PHP_EOL;
echo time_since(new DateTime('2014-11-10 13:05')) . PHP_EOL;
echo time_since(new DateTime('2114-11-10 13:05')) . PHP_EOL; //future
结果:
rr-@work:~$ php test.php
10 months 9 days
1 month 1 day
1 day 13 hours
13 hours 5 minutes
38 seconds
just now