所以,我有这个工作代码,它将MySQL日期转换为UNIX时间戳,并从当前日期()中减去它,以显示“自X以来经过的时间”计时器。 (从数据库中获取日期的部分缺失,因为它在另一个脚本中)
<?php
function time_elapsed($secs){
$bit = array(
' year' => $secs / 31556926 % 12,
' week' => $secs / 604800 % 52,
' day' => $secs / 86400 % 7,
' hour' => $secs / 3600 % 24,
' minute' => $secs / 60 % 60,
' second' => $secs % 60
);
foreach($bit as $k => $v){
if($v > 1)$ret[] = $v . $k . 's';
if($v == 1)$ret[] = $v . $k;
}
array_splice($ret, count($ret)-1, 0, 'and');
$ret[] = 'ago.';
return join(' ', $ret);
}
$nowtime = time() + 10; //add 10s to avoid error
$oldtime = strtotime($mysqltime2);
$time_elapsed = time_elapsed($nowtime-$oldtime)."\n";
echo wordwrap($time_elapsed,35,"<br />\n"); //split long line
?>
如果脚本是在MySQL日期的同一时间执行的话,我设法修复了报告丢失数组的错误,或者添加10秒到当前时间戳。
我遇到的另一个问题是脚本显示“和X秒”,即使它没有分钟/小时/天/等。 例如。 “和 X秒” “Y分钟和 X秒” “Z小时Y分钟和 X秒” “N天Z小时Y分钟和 X秒”
如果之前没有分钟/小时/等,我想在秒之前删除“和”。
有关如何解决此问题的任何提示?
答案 0 :(得分:0)
我能想到的最简单的是
$time_elapsed = time_elapsed($nowtime-$oldtime))."\n";
if($nowtime-$oldtime < 61){
$time_elapsed=str_replace('and ',' ',$time_elapsed);
}
答案 1 :(得分:0)
您只能在需要时拼接:
if( count($ret) > 1 ) {
array_splice($ret, count($ret)-1, 0, 'and');
}
答案 2 :(得分:0)
不确定这是否有帮助,但为什么不在mysql中执行大部分日期数学?
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
以下是我在网站的评论部分列出帖子之前所做的事情,它输出&#34; 2小时前发布的帖子&#34;等
SQL:
UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(made_on) as madeon
PHP(将查询传递给此处):
function seconds_to_textual_time_ago($seconds)
{
$hour = 60* 60;
$day = 24 * $hour;
$month = 30 * $day;
$year = 365 * $day;
switch(true)
{
case ($seconds < 60) :
$time_ago = "Less than 1 minute ago";
break;
case ($seconds >= 60 && $seconds < $hour):
$minutes = floor($seconds /60);
if ($minutes > 1)
$time_ago = "$minutes minutes ago";
else
$time_ago = "1 minute ago";
break;
case ($seconds >= $hour && $seconds < $day):
$hours = floor($seconds /$hour);
if ($hours > 1)
$time_ago = "$hours hours ago";
else
$time_ago = "1 hour ago";
break;
case ($seconds >= $day && $seconds < $month):
$days = floor($seconds /$day);
if ($days > 1)
$time_ago = "$days days ago";
else
$time_ago = "1 day ago";
break;
case ($seconds >= $month && $seconds < $year):
$months = floor($seconds /$month);
if ($months > 1)
$time_ago = "$months months ago";
else
$time_ago = "1 month ago";
break;
case ($seconds >= $year ):
$years = floor($seconds /$year);
if ($years > 1)
$time_ago = "$years years ago";
else
$time_ago = "1 year ago";
break;
default:
break;
}
return $time_ago;
}