5

I'm having some trouble calculating if time is past 15 minutes, on a date and time in my database. How can I check this?

I have this in my database (example):

2014-01-30 15:29:31

And then I get the date from PHP:

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

But how can I check if the time has passed 15 minutes, or if it's a different day?

I have this code so far:

$date = date("Y-m-d H:i:s");
$sql = "SELECT date FROM reset WHERE session_id = '".$sessid."' limit 1";
$result = mysql_query($sql);
$value = mysql_fetch_object($result);
$dbdate = $value->date;

$checkdate = strtotime($dbdate);
if ($checkdate - time() > 15 * 60) {
    error_log("15 mins passed");
}
2
  • Why are you using a database ... you should just store this in the users session variable
    – cmorrissey
    Jan 30, 2014 at 21:19
  • Because it's a password reset link, after 15 minutes the row will be set as expired. That's why I'm using a database.
    – Anders
    Jan 30, 2014 at 21:20

3 Answers 3

20

You can convert the date to a timestamp with strtotime (which supports the MySQL date format) and then compare it to the current timestamp from time.

$dbtimestamp = strtotime($datefromdb);
if (time() - $dbtimestamp > 15 * 60) {
    // 15 mins has passed
}

To compare the dates, you can use date to get the year/month/day from the timestamp and then compare them against the current date.

if (date("Y-m-d", $dbtimestamp) != date("Y-m-d")) {
    // different date
}
3
  • I don't think the time works. Look at the thread, I've updated it.
    – Anders
    Jan 30, 2014 at 21:18
  • Also just tried the date, for some reason it gives me this date '1969-12-31'.
    – Anders
    Jan 30, 2014 at 21:30
  • @Anders I just fixed a typo in the variable name, in case you copy-pasted my code. Jan 31, 2014 at 16:01
4

Using a DateTime object:

$dateTimeObject = new \DateTime($dateString);
//and subtract using an interval
$dateTimeObject->sub(new \DateInterval("PT15M"));
$newDateString = $dateTimeObject->format("Y-m-d H:i:s");
2

you cans use DATE_FORMAT functions.

$actual_minute = date("i");
$data = mysql_query("SELECT DATE_FORMAT(date,'%i') minutes FROM reset WHERE session_id = '".$sessid."'");
$database_minute = $data{'minutes'};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.