これは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"
編集:これが私の2回目の試みです
$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