Datetime comparison PHP/Mysql?

后端 未结 4 855
醉梦人生
醉梦人生 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:43

    the most efficient PHP/MySQL combined solution is:

    $date = date('Y-m-d H:i:s', strtotime('-15 minutes'));
    $data = $pdo->query("SELECT date_field > '$date' as expired from table")->fetchAll(PDO::FETCH_COLUMN);
    foreach($data as $expired) {
        if (!$expired) {
            // Still Valid
        }
    }
    
    0 讨论(0)
  • 2021-02-10 05:52

    Try this

    $interval = date_create($date_from_db)->diff(new \DateTime());
    if ($interval->format('%r%l')>15) {
        $result = false;
    } else {
        $result = true;
    }
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2021-02-10 06:00

    You have a solution for MYSQL in other answers, a good solution for PHP is:-

    $now = new \DateTime();
    $target = new \DateTime(getTimeStringFromDB());
    $minutes = ($target->getTimestamp() - $now->getTimestamp())/60;
    if($minutes < 15){
        // Do some stuff
    } else {
        //Do some other stuff
    }
    
    0 讨论(0)
提交回复
热议问题