这是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
答案 0 :(得分:0)
humanTiming()
函数需要一个UNIX时间戳,而不是格式化的日期,所以这样称之为:
$date1 = mysql_result($result,0,"date");
echo humanTiming( strtotime($date1));
使用您的样本日期output is:
6 months