Php 将时间戳转换为“X秒前”、“X分钟前”、“X小时前”等
如果php已经内置了功能,有人会这样做吗Php 将时间戳转换为“X秒前”、“X分钟前”、“X小时前”等,php,time,timestamp,Php,Time,Timestamp,如果php已经内置了功能,有人会这样做吗 谢谢,此功能没有内置功能……但以下功能可以完成此功能 <?php function nicetime($date) { if(empty($date)) { return "No date provided"; } $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
谢谢,此功能没有内置功能……但以下功能可以完成此功能
<?php
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 = "2009-03-04 17:45";
$result = nicetime($date); // 2 days ago
?>
只会在两天前回来
但是如果你想得到1秒前、10秒前的结果,你还需要在$date中加上秒数
$date = "2009-03-04 17:45:20";
$result = nicetime($date);
因此,当您添加一个新的db条目并立即刷新页面时,您将得到1秒前的结果,而不是本机生成的结果,但我对的回答可能对您有用。刚刚找到一个函数,该函数正是我所需要的,可能是as的副本
$date = "2009-03-04 17:45:20";
$result = nicetime($date);