我不知道为什么,但以下是4小时前返回以下所有日期/时间
function ago($timestamp){
$difference = floor((time() - strtotime($timestamp))/86400);
$periods = array("second", "minute", "hour", "day", "week", "month", "years", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
for($j = 0; $difference >= $lengths[$j]; $j++)
$difference /= $lengths[$j];
$difference = round($difference);
if($difference != 1)
$periods[$j].= "s";
$text = "$difference $periods[$j] ago";
return $text;
}
我发送的日期是
"replydate": "29/07/2012CDT04:54:27",
"replydate": "29/07/2012CDT00:20:10",
答案 0 :(得分:1)
功能strtotime
不支持此类格式'29/07/2012CDT00:20:10'
。使用这样的语法'0000-00-00 00:00:00'
。并且不需要86400
。所有代码:
function ago($timestamp){
$difference = time() - strtotime($timestamp);
$periods = array('second', 'minute', 'hour', 'day', 'week', 'month', 'years', 'decade');
$lengths = array('60', '60', '24', '7', '4.35', '12', '10');
for($j = 0; $difference >= $lengths[$j]; $j++) $difference /= $lengths[$j];
$difference = round($difference);
if($difference != 1) $periods[$j] .= "s";
return "$difference $periods[$j] ago";
}
echo ago('2012-7-29 17:20:28');
答案 1 :(得分:1)
不如编写自己的日期/时间函数,最好使用像PHP DateTime class这样的标准实现。让时间计算正确有一些微妙之处,例如时区和夏令时。
<?php
date_default_timezone_set('Australia/Melbourne');
// Ideally this would use one of the predefined formats like ISO-8601
// www.php.net/manual/en/class.datetime.php#datetime.constants.iso8601
$replydate_string = "29/07/2012T04:54:27";
// Parse custom date format similar to original question
$replydate = DateTime::createFromFormat('d/m/Y\TH:i:s', $replydate_string);
// Calculate DateInterval (www.php.net/manual/en/class.dateinterval.php)
$diff = $replydate->diff(new DateTime());
printf("About %d hour%s and %d minute%s ago\n",
$diff->h, $diff->h == 1 ? '' : 's',
$diff->i, $diff->i == 1 ? '' : 's'
);
?>