Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Checking if timestamp is less than 30 minutes old

Tags:

php

timestamp

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.

like image 651
user1511331 Avatar asked Jul 18 '12 20:07

user1511331


3 Answers

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.

like image 81
Mike Flynn Avatar answered Nov 04 '22 01:11

Mike Flynn


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.

like image 45
WWW Avatar answered Nov 04 '22 01:11

WWW


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)
like image 1
Bandana Sahu Avatar answered Nov 04 '22 03:11

Bandana Sahu