2010-06-21 58 views
0

我试图在用户添加条目时将时间保存在数据库中。每次运行time()函数时,它都会打印(或返回)1277155717,其中代表1969.php和1969中的时间函数

我想知道是否有一种方法可以将时间保存到数据库中,以表示今天的实际日期此时。

我使用

/* Works out the time since the entry post, takes a an argument in unix time (seconds) */ 
function time_since($original) { 
    // array of time period chunks 
    $chunks = array(
     array(60 * 60 * 24 * 365 , 'year'), 
     array(60 * 60 * 24 * 30 , 'month'), 
     array(60 * 60 * 24 * 7, 'week'), 
     array(60 * 60 * 24 , 'day'), 
     array(60 * 60 , 'hour'), 
     array(60 , 'minute'), 
    ); 

    $today = time(); /* Current unix time */ 
    $since = $today - $original; 

    // $j saves performing the count function each time around the loop 
    for ($i = 0, $j = count($chunks); $i < $j; $i++) { 

     $seconds = $chunks[$i][0]; 
     $name = $chunks[$i][1]; 

     // finding the biggest chunk (if the chunk fits, break) 
     if (($count = floor($since/$seconds)) != 0) { 
      // DEBUG print "<!-- It's $name -->\n"; 
      break; 
     } 
    } 

    $print = ($count == 1) ? '1 '.$name : "$count {$name}s"; 

    if ($i + 1 < $j) { 
     // now getting the second item 
     $seconds2 = $chunks[$i + 1][0]; 
     $name2 = $chunks[$i + 1][1]; 

     // add second item if it's greater than 0 
     if (($count2 = floor(($since - ($seconds * $count))/$seconds2)) != 0) { 
      $print .= ($count2 == 1) ? ', 1 '.$name2 : ", $count2 {$name2}s"; 
     } 
    } 
    return $print; 
} 

为了显示分钟,年,月,等的数量,因为有人评论张贴的功能,它返回(40岁,6月前),当我通过函数time()的值;

+1

“1277155717'的时间戳是'2010年6月21日星期一,21:28:37(GMT)' – vimist 2010-06-21 21:41:13

+0

是的,那么上面的函数有什么问题(感谢验证这个btw) – user220755 2010-06-21 21:45:46

+0

什么让你沉沦' 1277155717'在1969年有一段时间? – jigfox 2010-06-21 21:48:11

回答

1

为什么你不只是使用SQL的timestamp类型,即

INSERT INTO posts (content, created) VALUES ("Sample post", NOW()); 
+0

我想能够使用php函数(time())。但是它返回的是1277155717,这不是它当前应该返回的数字。我非常肯定上面的功能是正确的,所以它不应该说40年6个月 – user220755 2010-06-21 21:40:19

+1

这是“它应该返回当前时间的真实数字”。 查看http://www.unixtimestamp.com/获取当前时间戳。 – cypher 2010-06-21 21:43:20

+0

然后你能帮我检查一下上面的函数有什么问题:)? – user220755 2010-06-21 21:45:25

0

你想要一个时间戳或实际格式化的时间吗?'

如果是后者,试试这个:

$time = date("h:i:s"); 
+0

时间戳不格式化的时间 – user220755 2010-06-21 21:38:19

0

要非常小心,你开始实现自己计算日期之前。总会有奇怪的情况需要处理。在你的例子中,它看起来像你没有考虑夏令时或闰年。我不知道这对你是否重要。

如果你使用一些库为你做日期计算,你的机会会更好。我建议你首先看看PHP中的date_diff function。我不知道它是否处理夏令时和闰年,但这是我开始的地方。