php 将时间戳与数据库中的当前时间进行比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/14647338/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Comparing timestamp to current time from database
提问by Josh Boothe
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:
我需要根据数据库中的日期时间测试当前时间,如果已经是 30 分钟,则执行代码,如果不是,则不要。这就是我所处的位置,我被困住了:
$link = mysqli_connect("hostname", "username", "password", "database");
$q = "SELECT id FROM dwCache ORDER BY id DESC LIMIT 1";
$qu = mysqli_query($link, $q);
while($row=mysqli_fetch_array($qu, MYSQL_ASSOC)){
        $id = $row['id'];
        $cache = $row['cache'];
        $timest = $row['time'];
    }
$newTime = 
$difference = $timest
if($timest >= )
As you can see towards the bottom I lose it as I am not sure what to do.
正如你在底部看到的那样,我失去了它,因为我不知道该怎么做。
$timestreturns : 2013-02-01 12:36:01as the format Y-m-dh-i-s
$timest返回:2013-02-01 12:36:01作为格式Y-m-dh-i-s
Apologies on double post, other deleted.
对双发道歉,其他已删除。
回答by Sankalp Mishra
First convert $timestto timestamp
首先转换$timest为时间戳
$time = strtotime($timest);
$curtime = time();
if(($curtime-$time) > 1800) {     //1800 seconds
  //do stuff
}
回答by Dave
do it all in sql statement
在 sql 语句中完成所有操作
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.
这将返回表中时间列在 30 分钟之前的所有内容。
回答by Vlad Preda
I like to use unix timestampsin this situation.
在这种情况下,我喜欢使用unix 时间戳。
$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.
这基本上计算了当前时间与表列中的时间之间的差异。如果它高于 1800(30 分钟),它将选择该行,并执行您的 PHP 代码。
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.
使用它代替您开始执行的 PHP 检查有一些优点。您将选择更少的行,从而占用更少的内存。
PS:
PS:
Thumbs up for using MySQLi!
竖起大拇指使用MySQLi!
回答by Andrej Bestuzhev
SELECT id FROM dwCache ORDER BY id DESC LIMIT 1
you'll get only idfield, it's the first.
The second, for time converting: MySQL convert datetime to Unix timestamp
你只会得到id字段,这是第一个。二、时间转换:MySQL将日期时间转换为Unix时间戳
Third: you can convert your time string using strtotimefunction.
第三:您可以使用strtotime函数转换时间字符串。

