MySQL MySQL日期比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6110862/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 19:59:45  来源:igfitidea点击:

MySQL date comparison

mysql

提问by stef

Dates are stored in DB as such: "2011-05-26 11:00:00" in a datetime field. I'd like to find all rows where the date is greater than the first of this month, ie: 2011-05-01 09:00:00

日期存储在 DB 中,如下所示:日期时间字段中的“2011-05-26 11:00:00”。我想找到日期大于本月第一天的所有行,即:2011-05-01 09:00:00

The date formats in the DB can not be changed. What MySQL function can I use to convert the date in the DB to a format that can handle comparison? I'm guessing the best format for "first of the month" is a unix timestamp?

数据库中的日期格式无法更改。我可以使用什么 MySQL 函数将数据库中的日期转换为可以处理比较的格式?我猜“本月第一天”的最佳格式是 unix 时间戳?

The time values in the dates are always present but only office hours, so from 09:00 to 17:00.

日期中的时间值始终存在,但只有办公时间,因此从 09:00 到 17:00。

回答by deceze

If it's stored in a DATETIMEfield, just query on WHERE date > '2011-05-01 09:00:00'.

如果它存储在一个DATETIME字段中,只需在 上查询WHERE date > '2011-05-01 09:00:00'

回答by George Cummins

$firstDayOfMonth = date( 'Y-m-d H:i:s', mktime(0,0,0,date('n'),1,date('Y'));
$query = "SELECT * FROM `table` WHERE `date` >= '$firstDayOfMonth'";

回答by Wesley van Opdorp

Something like this perhaps?

也许是这样的?

$oDateTime = new DateTime();
$sQuery = "SELECT * FROM table WHERE date >= ".$oDateTime->format("Y-m")."-01 09:00:00";

回答by Denis de Bernardy

Compare to the datetime directly:

直接与日期时间进行比较:

WHERE date_field >= '2011-05-01 00:00:00'

回答by YeJiabin

You can use TIMESTAMPDIFF function in MySQL to compare time,
FROM_UNIXTIME function to format Unix timestamp as date.

您可以使用 MySQL 中的 TIMESTAMPDIFF 函数来比较时间,使用
FROM_UNIXTIME 函数将 Unix 时间戳格式化为日期。

More mysql data and time functions and examples are available in MySQL Reference Manual date and time function.

更多 mysql 数据和时间函数和示例可在MySQL 参考手册日期和时间函数中找到

回答by Kris

DATETIMEfields can filtered just like integer fields, example:

DATETIME字段可以像整数字段一样过滤,例如:

SELECT * FROM `table` WHERE `date` > '2011-05-01 09:00:00'

In case you really want to convert to Unix timestamps, have a look at the UNIX_TIMESTAMPfunction.

如果您真的想转换为 Unix 时间戳,请查看UNIX_TIMESTAMP函数。

回答by Martin Vancura

I think that you can solve it, something like this:

我认为你可以解决它,像这样:

firstly, create first day of month in mysql format in php

首先,在php中以mysql格式创建一个月的第一天

$firsDay = date('Y-m-d 00:00:00', strtotime(date('Y-m').'-01 00:00:00'));

and then, use it in the query

然后,在查询中使用它

select * from something where date >= $firsDay