简体   繁体   English

与PHP和Mysql的日期比较

[英]Date comparison with PHP and Mysql

I have a table with a date field type date . 我有一个日期字段类型为date的表。

What I am trying to do is to do a comparison between the date from inside the table and the today date. 我想做的是在表格中的日期和今天之间进行比较。 If the date from the table is yesterday then insert the today date. 如果表中的日期是昨天,则插入今天。

The thing I'm not sure about is how to insert the data in the database so I can make the comparison. 我不确定的是如何在数据库中插入数据,以便进行比较。 here is what im thinking to do" 这是我在想的事情”

$d = time();
$x = mysql_querry("SELECT date FROM table where id = $id", $con);
while($y = myqsl_fetch_array($x)){
    $oldTime = $y['date']; 
}

if ($oldTime < $d){
$i = mysql_querry("INSERT INTO table (date) VALUES (CURDATE()) ", $con);
}

So, I'm not sure if $oldTime and $d can be compared like that, but I hope you guys get my point. 因此,我不确定是否可以像这样比较$oldTime and $d ,但我希望你们能理解我的意思。

Any ideas? 有任何想法吗?

Thanks 谢谢

You can't do in that way because the CURDATE() function return a date in a format like 2011-11-11 while time() returns the number of seconds since the January 1 1970 00:00:00 GMT. 您无法采用这种方式,因为CURDATE()函数以2011-11-11这样的格式返回日期,而time()返回自格林威治标准时间1970年1月1日00:00:00以来的秒数。

Anyway you can change the format of the time() to look like the CURDATE() using the date() function in this way: 无论如何,您可以使用date()函数以这种方式将time()的格式更改为CURDATE():

date('Y-m-d', time())

or even better, to get the current date, you can use just this line: 甚至更好,要获取当前日期,可以仅使用以下行:

date('Y-m-d')

To conclude, you can do the if in this way: 总之,您可以通过以下方式执行if:

if( strtotime($oldTime) < strtotime(date('Y-m-d')) )

or even better: 甚至更好:

if( strtotime($oldTime) < strtotime('now') )

To compare dates you can use strtotime($date); 要比较日期,可以使用strtotime($date); Where date can be a time(), mysql date or date('Ym-d'); 其中date可以是time(),mysql date或date('Ym-d'); string

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

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