time ago函数出错


error in time ago function

我有一个关于如何正确显示执行操作后经过的时间的问题,我有一种简单的注释系统,并且想添加在进行注释时正确显示的功能,我做了一些研究,发现了这一点:

 function ago($time)
{
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
  $now = date('Y-m-d h:i:s');
$now=strtotime($now);
if($now>$time)
   $difference     = $now - $time;
   elseif($time>$now)
    $difference     = $time - $now;
   $tense         = "ago";
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] ago ";
 }  

我现在更改了varibale$,以获得日期而不是时间的值,我有一个数据库,它有一个表,其中有一列处理时间,它被设置为datetime,所以我使用strtotime函数转换它,并通过函数发送它:

  $time=$row['time'];
  $time=strtotime($time);
  $ago=ago($time);

问题是它返回错误的时间段,例如,一分钟前发布评论返回两小时前,时区是正确的,我甚至打印了实际的日期和时间,例如,今天,我打印了这个:

  10 hours ago 2013-02-08 12:09:35 2013-02-08 02:18:52

正如你所看到的,时间差应该是两个小时左右,而不是十个小时。有人对如何做到这一点有更好的想法吗?或者有人能指出错误在哪里吗?

问题是您的mysql服务器和php.ini或在不同的时区。坚持一个。如果您无法更改服务器时区,那么您所要做的就是从mysql的datetime字段中获取值,然后使用PHP将其转换回UNIX时间戳。

// Start by setting the datetime zone for all your pages in PHP
date_default_timezone_set('Europe/Lisbon');
//Extract the datetime from the database regardless of the databases timezone.
$time = '2012-07-02 22:30:52';
//Then in PHP convert it into a UNIX timestamp.
$timestamp = strtotime($time);

现在,您的所有代码和时间都相对于您在date_default_timezone_set函数中指定的时区保持不变。

最好的方法就是根本不使用该函数,因为没有人真正想要它。只需显示发表评论的时间即可。(如果有人真的想要信息:比较的时钟在屏幕的右下角)。