可能重复:PHP:格式化时间Stackoverflow或Apple Mail样式
嗨,有人可以帮助我,我回应了mysql表中的时间戳,但我希望php计算时间戳,以天/小时/分钟 .
这是可能的,我仍然是php和mysql的新手,我正在学习,所以有人可以指导我正确的方向或告诉我如何做到这一点 . 谢谢
<? echo "{$news['date_added']}";?>
我希望输出为秒数:添加12秒前或添加3分钟前或添加4天前或添加4个月前
我认为脚本应该是这样的:
function nicetime($date)
{
if(empty($date)) {
return "No date provided";
}
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
$now = time();
$unix_date = strtotime($date);
// check validity of date
if(empty($unix_date)) {
return "Bad date";
}
// is it future date or past date
if($now > $unix_date) {
$difference = $now - $unix_date;
$tense = "ago";
} else {
$difference = $unix_date - $now;
$tense = "from now";
}
for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$difference /= $lengths[$j];
}
$difference = round($difference);
if($difference != 1) {
$periods[$j].= "s";
}
return "$difference $periods[$j] {$tense}";
}
$date = "{$news['content']}";
$result = nicetime($date); // 2 days ago ?>
3 回答
See it in action
参考
DateTime
DateInterval
请查看手册中的
date()
功能 . http://php.net/manual/en/function.date.php将打印例如:
如果您在MySQL表中的时间戳,您可以使用 FROM_UNIXTIME 函数以适当的格式获取它 .