以前的错误功能

时间:2013-02-08 11:25:49

标签: php

我有一个关于如何正确显示动作执行后经过的时间的问题,我有一个简单的评论系统,并希望添加正确显示评论时的功能,我做了一些研究并遇到了这样:

 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 $ now以获取日期的值而不是时间,我有一个数据库,其中有一个表有一个处理时间的列,它设置为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
如你所见,时间差应该是两个小时左右,而不是十个小时。有没有人对如何做到这一点有更好的想法,或者任何人都可以指出错误在哪里?

3 个答案:

答案 0 :(得分:1)

问题是你的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函数中指定的时区保持相关。

答案 1 :(得分:-1)

所以您想要的时间是“ 1小时前”或2周前,等等。 我在这里回答有关此网站xx time ago function doesn't work

上先前提出的问题

我希望这对您有帮助

答案 2 :(得分:-2)

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

相关问题