Datetime comparison PHP/Mysql?

后端 未结 4 857
醉梦人生
醉梦人生 2021-02-10 05:07

I\'m trying to make something like this:

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

if (datetime - system date          


        
4条回答
  •  再見小時候
    2021-02-10 05:53

    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
    }
    

提交回复
热议问题