Jagr
Jagr

Reputation: 512

Check if date() is greater than a specific time

In my code I pretty much send a token to the database with the

date('Y-m-d H:i:s');

function. But I am checking to see if the timestamp I sent if greater than 60 seconds if so i echo yes and else no. I keep getting no and I know its more than a minute because i time it. I've seen post about this but they're using specific dates and I am just going on when a user submits a form and checking if the token is 60 seconds old. Here is my code

php

<?php
    require_once('db_login.php');

    $stmtToken = $handler->prepare("SELECT * FROM email_token");
    $stmtToken->execute();
    $rowToken = $stmtToken->fetch();
    $date = $rowToken['time_stamp'];

     if($date > time() + 60) {
        echo 'yes';
     } else {
        echo 'no';
     }






?>

Upvotes: 0

Views: 1785

Answers (2)

sensorario
sensorario

Reputation: 21648

You can also play with dates in different manners. All four lines here are equivalent:

$now = (new \DateTime(date('Y-m-d H:i:s')))->getTimestamp();
$now = (new \DateTime('now'))->getTimestamp();
$now = (new \DateTime())->getTimestamp();
$now = time();

And then you can compare in this manner:

$tokenExpirationTimestamp = (new \DateTime($date))
    ->modify('+60 seconds')
    ->getTimestamp();

$isTokenExpired = $tokenExpirationTimestamp < time();

if ($isTokenExpired) {
    // ...
}

Upvotes: 2

Andreas
Andreas

Reputation: 23958

When you compare times and dates you can either use datetime or strtotime.
Using strings will not work as expected in all cases.
In comments you mentioned how you want to compare, and you need to add the 60 seconds to the "date", not the time().

if(strtotime($date) + 60 < time()) {

Upvotes: 1

Related Questions