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


PHP Checking if timestamp is less than 30 minutes old

我从数据库中得到一个项目列表,每个项目都有一个CURRENT_TIMESTAMP,我在timeago的帮助下将其更改为"x分钟前"。所以这很有效。但问题是,我也想在不到30分钟的商品上贴一条"新"的横幅。我如何获取生成的时间戳(例如:2012-07-18 21:11:12),并说如果距离当前时间不到30分钟,那么在该项目上回显"NEW"横幅。

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

示例:

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

我在这里使用strtotime()两次来获取mysql日期的unix时间戳,然后再次获取30分钟前的时间戳。如果30分钟前的时间戳大于mysql记录的时间戳,那么它一定是在30分钟后创建的。

使用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";
}

编辑:Mike是对的,我忘记了,无论出于什么原因,只有%a实际返回其类型的总数(在本例中为天)。所有其他都用于显示时间格式。我已经将以上内容扩展到实际工作中。

你也可以这样做-

$currentTime=time(); 

检查最后更新的时间是否为30分钟

last_updated_at <  $currentTime - (60*30)