Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datetime comparison PHP/Mysql?

I'm trying to make something like this:

if (datetime - system date > 15 minutes) (false)

if (datetime - system date <= 15 minutes) (true)

But I'm totally lost. I don't know how to make this operation in PHP.

I'd like to see how I can pick that DateTime from my database and check if it's between the last 15 minutes of my server's time.

The type of database is MySQL.


Finally, I managed to do it thanks to Sammitch and the other ones, here i leave the snippet:

$now    = time();
$target = strtotime($row[1]);
$diff   = $now - $target;

// 15 minutes = 15*60 seconds = 900
if ($diff <= 900) {
    $seconds = $diff;
} else {
    $seconds = $diff;
}
like image 263
Ralsho Avatar asked May 22 '14 17:05

Ralsho


People also ask

How do you compare time in PHP?

Interval Between Different Dates In order to compare those two dates we use the method diff() of the first DateTime object with the second DateTime object as argument. The diff() method will return a new object of type DateInterval .

How to compare timestamp with date in MySQL?

Use CONVERT() to Compare MySQL Timestamp Dates With the Date Parameter Only. The CONVERT() function can also compare the timestamp with the date only.


1 Answers

If your dates are already in MySQL you will want to do the comparison in the query because:

  1. MySQL has proper DATE types.
  2. MySQL has indexes for comparison.
  3. MySQL performs comparisons much faster than PHP.
  4. If you filter your data in the query then less, or no time is spent transferring superfluous data back to the application.

Below is the most efficient form. If there is an index on the date column it will be used.

SELECT *
FROM table
WHERE date > DATE_SUB(NOW(), INTERVAL 15 MINUTE)

Docs: DATE_SUB()

If you need to do it in PHP:

$now = time();
$target = strtotime($date_from_db);
$diff = $now - $target;
if ( $diff > 900 ) {
  // something
}

or, more succinctly:

if( time() - strtotime($date_from_db) > 900 ) {
  // something
}
like image 160
Sammitch Avatar answered Sep 20 '22 19:09

Sammitch