Krillex
Krillex

Reputation: 489

PHP Check if 10 minutes has gone by

I want to compare two dates with each other to see if 10 minutes has passed.

This is the code that I've got but I can't quite figure out how to do it.

I get the first date from my table (which is saved as a timestamp, example: 2017-03-26 22:33:45) and then I want to compare it with the time that is right now.

$sql = "SELECT saved_time from table1 where email = '$email'";
$stmt = $conn->prepare($sql);
$stmt->execute();
while($row = $stmt->fetch()) {
    $savedTime = $row[0];
}
$now = time();
if (/*10 minutes has passed between saved time and now*/) {
    echo "Your account is unlocked";
} else if (/*10 minutes hasn't passed*/) {
    echo "Your account is locked";
}

Upvotes: 0

Views: 4170

Answers (3)

Sachin PATIL
Sachin PATIL

Reputation: 745

Try This code:

    $timezone = "Asia/Kolkata";// Select Timezone as of your Preference or MySQL Server Timezone
    date_default_timezone_set($timezone);
    $sql = "SELECT saved_time from table1 where email = :email";
    $stmt = $conn->prepare($sql);
    $stmt->execute(array(':email' => $email));
    while($row = $stmt->fetch()) {
        $savedTime = $row[0];
    }

    // Uncomment below Line if $savedTime is in MySQL DATETIME Format
    // $savedTime = strtotime($savedTime);
    $now = time();

    if (round(($now - $savedTime) / 60,2) >= 10){
       echo "Your account is unlocked";
    } elseif (round(($now - $savedTime) / 60,2) < 10){
       echo "Your account is locked";
    }

Upvotes: 3

siddiq
siddiq

Reputation: 1711

If mysql solution is fine for you, then

select * from table T where TIMESTAMPDIFF(MINUTE,.saved_time,NOW()) > 10 

If you need it in php, then

$db_time = $row['saved_time'];//as you have stored in timestamp already
$curr_time = strtotime(date('Y-m-d H:i:s'));
$diff =  round(abs($db_time - $curr_time) / 60,2);
if($diff > 10)

Update

select now() as curr_time, saved_time from table where COND;

then in php

$diff = $curr_time-$saved_time;
if($diff > (10*60 ))

I am not sure whether this will work. But just an idea.

Upvotes: 0

Confidence
Confidence

Reputation: 2303

if $now = time(); #(this will generate a timestamp)

assuming $savedTime = $row[0]; is a MySQL date field, you can do

$savedTimeTimestamp= date("Y-m-d H:i:s", $savedTime);

...now 10 time 60 seconds is 10 minutes, so

if ($now > ($savedTimeTimestamp+600))

should do the job

Upvotes: 0

Related Questions