Comparing timestamp to current time from database

前端 未结 4 1392
感情败类
感情败类 2020-12-29 03:50

I need to test current time against a datetime from database, if it has been 30 mins then execute code, if not then dont. This is where I am at and I am stuck:



        
相关标签:
4条回答
  • 2020-12-29 04:22

    I like to use unix timestamps in this situation.

    $timest = date('u'); // gets the unix timestamp
    $q = "SELECT id 
          FROM `dwCache` 
          WHERE {$timest} - UNIX_TIMESTAMP(`timestamp_col`) > 1800";
    

    Explanation:

    This basically calculates the difference between the current time and the time in the table column. If it's higher than 1800 (30 minutes), it will select the row, and your PHP code will be executed.

    Advantages

    There are some advantages to using this instead of the PHP check you started doing. You will select fewer rows, thus occupy less memory.

    PS:

    Thumbs up for using MySQLi !

    0 讨论(0)
  • 2020-12-29 04:26

    do it all in sql statement

    SELECT id FROM `dqCache` WHERE `time`<DATE_SUB(NOW(), INTERVAL 30 MINUTE);
    

    This will return everything from your table where the time column is before 30 minutes before now.

    0 讨论(0)
  • 2020-12-29 04:28

    First convert $timest to timestamp

    $time = strtotime($timest);
    
    $curtime = time();
    
    if(($curtime-$time) > 1800) {     //1800 seconds
      //do stuff
    }
    
    0 讨论(0)
  • 2020-12-29 04:34
    SELECT id FROM dwCache ORDER BY id DESC LIMIT 1
    

    you'll get only id field, it's the first. The second, for time converting: MySQL convert datetime to Unix timestamp

    Third: you can convert your time string using strtotime function.

    0 讨论(0)
提交回复
热议问题