这是 arnorhs 的代码,它将日期和时间转换为“人类”时间,例如“3 天前”:
$time = strtotime('2010-04-28 17:25:43');
echo 'event happened '.humanTiming($time).' ago';
function humanTiming ($time)
{
$time = time() - $time; // to get the time since that moment
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second');
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
手动输入日期时效果很好。
但是当我使用一个包含 MySQL 数据库 DATETIME 的字符串时,结果总是“42 年”:
// MySQL date is: 2012-01-02 11:22:33
$date1 = mysql_result($result,0,"date");
$date2 = date("Y:m:d H:i", strtotime($date1));
echo humanTiming($date2);
// Result: "42 years"
编辑:这是我的第二次尝试
$date1 = mysql_result($result,0,"date");
$date2 = "2012-01-02 11:22:33";
echo "The first date is $date1 which is ";
echo humanTiming( strtotime($date1));
echo ", and the second date is $date2 which is ";
echo humanTiming( strtotime($date2));
// Result: The first date is 2012-01-02 11:22:33 which is , and the second date is 2012-01-02 11:22:33 which is 6 months