用PHP存储时间

时间:2011-05-17 00:00:19

标签: php mysql time

存储在table1中的

数据带有时间戳。用于存储时间戳的语法是NOW()。存储的时间格式为2011-05-17 00:46:19。我的问题是我如何按时间访问最新数据,如何显示时间说“10分钟前存储的数据”或5秒前或1天等。我使用的是MySQL和PHP。

4 个答案:

答案 0 :(得分:3)

SELECT * FROM table1 
WHERE table1.TimePosted BETWEEN NOW() AND DATE_SUB(NOW(),INTERVAL 10 MIN);

链接:http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add

答案 1 :(得分:0)

mysql_result()获得结果时,请使用以下内容:

$t = strtotime($value_from_db); // now you have a Unix epoch time.
$minutediff = (mktime()-$t)/60; // $minutediff minutes ago.

答案 2 :(得分:0)

SELECT * FROM table1 WHERE table1.TimePosted >= NOW() - INTERVAL 10 MIN

答案 3 :(得分:0)

这是我之前在我的代码中所做的事情,可能是有用的

$sql  ="select datetimecol from table1 where x=y, etc";

$result = mysql_query($sql);
// TODO check for mysql errors

list($datetimecol) = mysql_fetch_row($result);

$timestamp = strtotime($datetimecol);

$diff = time() - $timestamp; 

if ($diff < 600) {
    // less then 10 minutes
    return 'Hot off the press';
} else if ($diff < 3600) {
    // less then 1 hour
    return sprintf('%d minutes ago', ($diff / 60));
} else if ($diff < 7200) {
    // less then 2 hours
    return '1 hour ago';        
} else if ($diff < 43200) {
    // less then 12 hours
    return sprintf('%d hours ago', ($diff / 3600));
} else if ($diff < 86400) {
    // less then 24 hours and on same day
    if (date('j') == date('j', $timestamp)) {
        return 'Today';
    } else {
        return 'Yesterday';
    }       
} else if ($diff < 172800) {
    // less then 48 hours and on next day
    if (date('i') == date('j', $timestamp + (60 * 60 * 24))) {
        return 'Yesterday';
    } else {
        return date('l', $timestamp);
    }
} else if ($diff < 604800) {
    return date('l', $timestamp);       
} else {
    return date('r', $timestamp);
}