prk
prk

Reputation: 3809

Add current time to database and when reading it later check if that time has passed

So I'd like to add the current time to the database, to a specific user when he does something, and later on read it, and check if that time has passed (by checking current time and substracting that from the one in database; to check if it has passed or not)

So how would I do this? I tried with something like this:

$date = date("YmWjis");
$calculate = $date - $info['lastvisit'];
if($calculate <= -1)
{
echo "you need to wait before visiting again"; // (just an example)
} else {
//do something
}

I also tried both:

!$calculate < 0
$calculate < 0

etc. But I can't get it to work. Can anyone help me? :P

edit for Parag;

$date = date("YmWjis");
$dote = date("YmWjis") + $time; // ($time is set earlier and is 30 seconds)
echo "wait " . $date = $date - $dote . " seconds until next visit";

work? It says like "wait 20138269786674 seconds until next visit".

Upvotes: 0

Views: 44

Answers (3)

Jonathan M
Jonathan M

Reputation: 17451

Don't use a database. This does the job without the db overhead. It uses PHP sessions.

<?php

session_start();
if (!isset($_SESSION['lastVisitTime'])) {
    $_SESSION['lastVisitTime']=new DateTime();
} else {
    $now=new DateTime();
    if ($_SESSION['lastVisitTime']->diff($now) > $someMaxValueYouDefine) {
        echo "You must wait before visiting again.";
    }
}

Upvotes: 0

Parag Tyagi
Parag Tyagi

Reputation: 8960

$db_time = "2014/04/28 15:15:15";
$cur_time = "2014/04/28 18:15:15";

if(strtotime($cur_time) > strtotime($db_time))
{
     // Current time exceeds DB time
     $diff = date('Y/m/d H:i:s', strtotime($cur_time)-strtotime($db_time));
     echo $diff;
}
else
{
    // Current time didn't exceeds DB time
}


UPDATE

 $date = strtotime(date("YmWjis"));
 $dote = strtotime(date("YmWjis")) + $time; // ($time is set earlier and is 30 seconds)
 echo "wait " . $date = $date - $dote . " seconds until next visit";


DEMO

http://3v4l.org/LBIXu

Upvotes: 0

Piotr Olaszewski
Piotr Olaszewski

Reputation: 6204

You can try something like this:

$dateDiff = new DateTime("2014-04-27 22:00:15");

$date = new DateTime();
$diff = $date->diff($dateDiff);
if($diff->invert == 0)
{
echo "you need to wait before visiting again"; // (just an example)
} else {
//do something
}

Upvotes: 1

Related Questions