简体   繁体   English

MySQL date_format和日期范围

[英]MySQL date_format and date ranges

I am trying to generate a MySQL query that would display records between a specific date range. 我正在尝试生成一个MySQL查询,该查询将显示特定日期范围之间的记录。

Catering for a predominantly British userbase I have to format dates in a day-month-year manner. 为了满足主要是英国用户的需求,我必须以日-月-年的方式格式化日期。

As a result, I am storing dates as follows: 结果,我将日期存储如下:

$timestamp = date("d-m-Y H:i:s");

Now I am trying to run a MySQL query to return results between a set date range. 现在,我正在尝试运行MySQL查询,以在设定的日期范围之间返回结果。 Time of day isn't so much of an issue for this specific query. 对于这个特定的查询而言,一天中的时间并不是什么大问题。

I have come up with the following which doesn't seem to generate any results. 我想出了以下似乎没有产生任何结果的方法。

SELECT * FROM table WHERE DATE_FORMAT(`timestamp`, '%d-%m-%Y %H:%i:%s') BETWEEN '01-01-2015 00:00:00' AND '31-12-2015 23:59:00'

I have ensured that date_format contents matches the same values of php date() variable yet it still doesn't display anything! 我已确保date_format内容与php date()变量的值相同,但仍不显示任何内容!

It might be worth noting that the timestamp column is set to be a varchar(255) for type. 可能值得注意的是,timestamp列的类型设置为varchar(255)

Any ideas how I could achieve this? 有什么想法我能做到这一点吗?

Choose the right percentage!. 选择正确的百分比! Use %m instead of %c . 使用%m代替%c %m is zero-padded (as you need it, ie 01 - 12 ) whereas %c is not (ie 1 - 12 ). %m是零填充(如你需要它,即01 - 12 ),而%c不是(即1 - 12 )。

See here for details. 详情请见此处


Update: 更新:

Sorry, the above is not true, as you store your dates as strings. 抱歉,上述内容不正确,因为您将日期存储为字符串。 I answered too quickly. 我回答得太快了。

The problem is that you are comparing strings. 问题是您正在比较字符串。 So '14-02-2017' is before '24-12-2015'. 因此,“ 14-02-2017”早于“ 24-12-2015”。 Thus you have to convert your string into a date_time value as well: 因此,您还必须将字符串转换为date_time值:

str_to_date(`timestamp`, '%d-%m-%Y %H:%i:%s')

Then you have to compare this with the values given, converted to the type date_time: 然后,您必须将其与给定的值进行比较,并将其转换为date_time类型:

... where str_to_date(`timestamp`, '%d-%m-%Y %H:%i:%s') 
  between str_to_date('01-01-2015 00:00:00', '%d-%m-%Y %H:%i:%s')
      and str_to_date('31-12-2015 23:59:00', '%d-%m-%Y %H:%i:%s');

However, I would strongly suggest that you store your date in DATE_TIME columns and only convert them during INSERT (with STR_TO_DATE) and SELECT (with DATE_FORMAT). 但是,我强烈建议您将日期存储在DATE_TIME列中,并且仅在INSERT(使用STR_TO_DATE)和SELECT(使用DATE_FORMAT)期间进行转换。

replace your with this one: 用这个替换您的:

SELECT * FROM table WHERE DATE_FORMAT(FROM_UNIXTIME(timestamp), '%d-%m-%Y %h:%i:%s') 
BETWEEN '01-01-2015 00:00:00' AND '31-12-2015 23:59:00'

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

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