我正在尝试创建一个将日期与当前时间进行比较的函数,并返回格式正确的字符串. 我已经在仓促中编写了一些代码并且它可以工作,但我正在尝试找到一种更有效的方法.这是我的代码:
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;
}
解决方法: 我使用的一些代码,它永远不会失败,只需将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;
}
(编辑:北几岛)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|