我正在尝试创建一个将日期与当前时间进行比较的函数,并返回格式正确的字符串 我已经在仓促中编写了一些代码并且它可以工作,但我正在尝试找到一种更有效的方法。这是我的代码:
function _formatDate($dateStr)
{
$timestr = "";
$t= time() - strtotime($dateStr);
if($t < 60) {
$timestr = "{$t} seconds ago";
}
elseif ($t <120) {
$timestr = "about a minute ago";
}
elseif ($t < 3600) {
$minute = floor($t/60);
$timestr = "{$minute} minutes ago";
}
elseif ($t < 7200) {
$timestr = " about an hour ago";
}
elseif ($t < 86400) {
$hour = floor($t/3600);
$timestr = "{$hour} hours ago";
}
elseif ($t < 172800) {
$timestr = "a day ago";
}
elseif ($t < 2592000) {
$day = floor($t/86400);
$timestr = "{$day} days ago";
}
elseif ($t < 5184000){
$timestr = "about a month ago";
}
else {
$month = floor($t/2592000);
$timestr = "{$month} months ago";
}
return $timestr;
}
答案 0 :(得分:4)
我使用的一些代码并且它永远不会失败,只是将Unix时间戳放入,如果你在函数中使用第二个参数可以是“to”条件
echo timeDiffrence('1300392875');
function timeDiffrence($from, $to = null){
$to = (($to === null) ? (time()) : ($to));
$to = ((is_int($to)) ? ($to) : (strtotime($to)));
$from = ((is_int($from)) ? ($from) : (strtotime($from)));
$units = array
(
"y" => 29030400, // seconds in a year (12 months)
"month" => 2419200, // seconds in a month (4 weeks)
"w" => 604800, // seconds in a week (7 days)
"d" => 86400, // seconds in a day (24 hours)
"h" => 3600, // seconds in an hour (60 minutes)
"m" => 60, // seconds in a minute (60 seconds)
"s" => 1 // 1 second
);
$diff = abs($from - $to);
$suffix = (($from > $to) ? ("from now") : ("ago"));
foreach($units as $unit => $mult)
if($diff >= $mult)
{
//$and = (($mult != 1) ? ("") : ("and "));
$output .= "".$and.intval($diff / $mult)."".$unit.((intval($diff / $mult) == 1) ? ("") : (""));
$diff -= intval($diff / $mult) * $mult;
}
$output .= " ".$suffix;
$output = substr($output, strlen(""));
if($output =='go' || $output ==' ago'){$output = 'A few secs ago';}
return $output;
}
答案 1 :(得分:1)
我建议你在javascript中使用它。您可以使用TimeAgo插件进行jquery。关于这一点很酷的是它将在客户端实时更新而不需要任何页面刷新。这很简单易用,符合您的要求。