简体   繁体   English

PHP中的MySQL日期比较

[英]MySQL date comparison from PHP

I would very much appreciate your help. 非常感谢您的帮助。

I have a mysql db that contains a Datetime field. 我有一个包含Datetime字段的mysql数据库。 In that field I have a particular date and time, for example: 在该字段中,我有一个特定的日期和时间,例如:

2013-10-03 22:28

I then have a PHP script that gets a particular date and time from the $_GET command, values separately: year, month, day, hour, minute. 然后,我有了一个PHP脚本,该脚本从$_GET命令获取特定的日期和时间,其值分别为:年,月,日,小时,分钟。

From this GET I created a Date as follows: 通过此GET,我创建了一个Date,如下所示:

$datum = $year."-".$month."-".$day." ".$hour.":".$minute.":".$seconds;
$date = date('Y-m-d H:i',strtotime($datum));

What I need to do now is somehow compare this new date I created with the last date value in the database (the most recent). 我现在需要做的是以某种方式将我创建的这个新日期与数据库中的最后一个日期值(最新)进行比较。 The point is that after I compare this I want to check whether the last value in the db is older than 5 minutes and only then do a particular action (insert new row), and if the last date in the db is newer than 5 minutes, do nothing. 关键是在比较之后,我想检查数据库中的最后一个值是否早于5分钟,然后才执行特定操作(插入新行),以及数据库中的最后日期是否比5分钟新。 , 没做什么。

使用“从tblname中选择max(datetime_field)”来获取Datetime字段的最新值。

$now = new DateTime();
$dateFromDB = new DateTime($someValueFromYourDataBase);

// subtract 5 minutes from now and compare with the stored timestamp
if ($now->sub(new DateInterval('PT5i') > $dateFromDB) {
    // database timestamp is older - do something
}

you can use SQL like this: 您可以这样使用SQL:

select count(*) from `table` where `datefield` >= '$date'

$date can be calculated like $ date可以像这样计算

 $date = date('Y-m-d H:i', strtotime($datum) - 5*60);

5*60 - it is 5 minutes 5 * 60-5分钟

for performance reason I suggest you to add index to datefield and change select like: 出于性能原因,我建议您将索引添加到datefield并更改选择,例如:

select `datefield` from `table` where `datefield` >= '$date' limit 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM