2012-11-22 48 views
19

我使用了Google,并尝试了几种比较日期的方法,但很遗憾没有按预期得到结果。我有记录的当前状态像下面:mysql与date_format的日期比较

 mysql> select date_format(date(starttime),'%d-%m-%Y') from data; 

       +-----------------------------------------+ 
       | date_format(date(starttime),'%d-%m-%Y') | 
       +-----------------------------------------+ 
       | 28-10-2012        | 
       | 02-11-2012        | 
       | 02-11-2012        | 
       | 02-11-2012        | 
       | 03-11-2012        | 
       | 03-11-2012        | 
       | 07-11-2012        | 
       | 07-11-2012        | 

我想比较的日期,因此这样做:

 mysql> select date_format(date(starttime),'%d-%m-%Y') from data where date_format(date(starttime),'%d-%m-%y') >= '02-11-2012'; 
       +-----------------------------------------+ 
       | date_format(date(starttime),'%d-%m-%Y') | 
       +-----------------------------------------+ 
       | 28-10-2012        | 
       | 02-11-2012        | 
       | 02-11-2012        | 
       | 02-11-2012        | 
       | 03-11-2012        | 
       | 03-11-2012        | 
       | 07-11-2012        | 
       | 07-11-2012        | 

我认为,结果不应该包括'28 -10-2012' 。任何建议?提前致谢。

回答

37

您的格式根本不是什么排序一个开始 - 你比较和字符串“28-10-2012” 比“2012年2月11日”更大。

相反,您应该将日期作为日期进行比较,然后仅将它们转换为您的目标格式输出。

试试这个:

select date_format(date(starttime),'%d-%m-%Y') from data 
where date(starttime) >= date '2012-11-02'; 

(输入必须始终年 - 月 - 值的形式,按照the documentation

注意,如果starttimeDATETIME场,您可能希望考虑改变查询以避免重复转换。 (优化可能是足够的,以避免它聪明,但它是值得一试。)

select date_format(date(starttime),'%d-%m-%Y') from data 
where starttime >= '2012-11-02 00:00:00'; 

(请注意,这是不寻常的格式化日期作为d-m-Y入手 - 这将是更好的,一般使用y-M-d,作为ISO-8601标准等。但是,上面的代码做你问对的问题。)

+0

非常感谢,这正是我正在寻找:)。 –

+1

@MahmoudGamal:你的编辑没有意义。使用Syntax'date'2012-11-02'' **指定日期文字是**有效的(实际上它是指定日期文字的SQL标准)。看到这里:http://sqlfiddle.com/#!2/d41d8/4020 –

+0

@JonSkeet:你也可以使用SQL标准文字指定日期时间字面值:'timestamp'2012-11-02 00:00:00' '(而不是使用“普通”字符串)。 –

1

使用2012年11月2日,而不是2012年2月11日,你将不再需要DATE_FORMAT()了

0

使用以下方法:

public function dateDiff ($date1, $date2) { 
/* Return the number of days between the two dates: */ 
    return round(abs(strtotime($date1)-strtotime($date2))/86400); 
} 
/* end function dateDiff */ 

这将有助于!