这将使用您的逻辑为您提供经过的时间并返回 1 week 5 days 21 hours 4 minutes 36 seconds
使用 strtotime(),我将时间转换为相对于 1970 年 1 月 1 日的数字。您现在可以与 time() 进行比较。我还减去了每个步骤中经过的时间量,以便它可以继续找到较小的增量。
这段代码会产生:
1 week
1 year
20 minutes 38 seconds
'
<?php
echo timePassed("2014-04-03 19:21:30") . "<br>";
echo timePassed("2013-02-03 19:21:30") . "<br>";
echo timePassed("2014-04-16 16:20:00") . "<br>";
function timePassed($time){
$time = time() - strtotime($time);
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
$return = "";
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
$time -= ($numberOfUnits * $unit);
$return .= $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'') . " ";
if ($unit > 60){
// return if match greater than minutes
return $return;
}
}
return $return;
}
?>
要跟进您的上一个请求,以下代码应该足以让您根据需要对其进行修改。此代码将产生:
1 week
2013-02-03 19:21:30
23 hours
.
<?php
echo timePassed("2014-04-03 19:21:30") . "<br>";
echo timePassed("2013-02-03 19:21:30") . "<br>";
echo timePassed("2014-04-16 16:20:00") . "<br>";
function timePassed($time){
$origtime = $time;
$time = time() - strtotime($time);
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
$return = "";
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
$time -= ($numberOfUnits * $unit);
$return .= $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'') . " ";
if ($unit > 60){
// return if match greater than hours
if ($unit > 2592000 ) {
// if units greater than one month, show the original time
return $origtime;
}
elseif ($unit == 2592000 && $numberOfUnits > 1){
// if units is months, show the original time if more than one month
return $origtime;
}
else {
// units greater than minutes, show the time without further detail
return $return;
}
}
}
return $return;
}
?>