简体   繁体   中英

PHP Checking if timestamp is less than 30 minutes old

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.

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

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.

Try something like this, using PHP's DateTime object:

$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 %a actually 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.

You can do like this also -

$currentTime=time(); 

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

last_updated_at <  $currentTime - (60*30)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM