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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11549742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:45:08  来源:igfitidea点击:

PHP Checking if timestamp is less than 30 minutes old

phptimestamp

提问by user1511331

I'm getting a list of items from my database, each has a CURRENT_TIMESTAMP which i have changed into 'x minutes ago' with the help of timeago. So that's working fine. But the problem is i also want a "NEW" banner on items which are less than 30 minutes old. How can i take the generated timestamp (for example: 2012-07-18 21:11:12) and say if it's less than 30 minutes from the current time, then echo the "NEW" banner on that item.

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

回答by Mike Flynn

Use strtotime("-30 minutes") and then see if your row's timestamp is greater than that.

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

Example:

例子:

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

I'm using strtotime() twice here to get unix timestamps for your mysql date, and then again to get what the timestamp was 30 minutes ago. If the timestamp from 30 mins ago is greater than the timestamp of the mysql record, then it must have been created more than 30 minutes go.

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

回答by Crontab

Try something like this, using PHP's DateTimeobject:

尝试这样的事情,使用 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";
}

Edit:Mike is right, I forgot that for whatever reason, only %aactually returns the total of its type (in this case days). All the others are for displaying time formatting. I've extended the above to actually work.

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

回答by Bandana Sahu

You can do like this also -

你也可以这样做——

$currentTime=time(); 

to check the last updated time is 30 minute old or not

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

last_updated_at <  $currentTime - (60*30)