PHP检查时间戳是否小于30分钟

时间:2012-07-18 20:27:57

标签: php timestamp

我从我的数据库中获取了一个项目列表,每个项目都有一个CURRENT_TIMESTAMP,在timeago的帮助下,我已经将其更改为'x分钟前'。所以这很好。但问题是我还想要一个不到30分钟的物品的“新”横幅。如何获取生成的时间戳(例如:2012-07-18 21:11:12)并说明距离当前时间是否少于30分钟,然后回显该项目上的“新”横幅。

3 个答案:

答案 0 :(得分:51)

使用strtotime(“ - 30分钟”),然后查看您的行的时间戳是否大于该值。

示例:

<?php
if(strtotime($mysql_timestamp) > strtotime("-30 minutes")) {
 $this_is_new = true;
}
?>

我在这里使用strtotime()两次为你的mysql日期获取unix时间戳,然后再次获得30分钟前的时间戳。如果30分钟前的时间戳大于mysql记录的时间戳,那么它的创建时间必须超过30分钟。

答案 1 :(得分:6)

尝试这样的事情,使用PHP的DateTime对象:

$now = new DateTime();
$then = DateTime($timestamp); // "2012-07-18 21:11:12" for example
$diff = $now->diff($then);
$minutes = ($diff->format('%a') * 1440) + // total days converted to minutes
           ($diff->format('%h') * 60) +   // hours converted to minutes
            $diff->format('%i');          // minutes
if ($minutes <= 30) {
    echo "NEW";
}

编辑:迈克是对的,我忘记了无论出于何种原因,只有%a实际上会返回其类型的总数(在这种情况下是几天)。所有其他用于显示时间格式。我已将上述内容扩展到实际工作中。

答案 2 :(得分:0)

您也可以这样做-

$currentTime=time(); 

检查上次更新时间是否早于30分钟

last_updated_at <  $currentTime - (60*30)
相关问题