在 MySQL 中解析日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3296725/
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
Parse date in MySQL
提问by Daniel Vassallo
How to convert the following into date for insertion/update into a TIMESTAMPor DATEfield in MySQL?
如何将以下内容转换为插入/更新到MySQL 中的TIMESTAMPorDATE字段的日期?
'15-Dec-09'
DATE_FORMAT()is used to format date, but not the other way around.
DATE_FORMAT()用于格式化日期,但反之则不然。
回答by Daniel Vassallo
You may want to use the STR_TO_DATE()function. It's the inverse of the DATE_FORMAT()function.
您可能想要使用该STR_TO_DATE()功能。这是DATE_FORMAT()函数的反函数。
STR_TO_DATE(str,format)
This is the inverse of the
DATE_FORMAT()function. It takes a stringstrand a format stringformat.STR_TO_DATE()returns aDATETIMEvalue if the format string contains both date and time parts, or aDATEorTIMEvalue if the string contains only date or time parts. If the date, time, or datetime value extracted fromstris illegal,STR_TO_DATE()returnsNULLand produces a warning.
STR_TO_DATE(字符串,格式)
这是
DATE_FORMAT()函数的反函数。它需要一个字符串str和一个格式字符串format。如果格式字符串包含日期和时间部分,则STR_TO_DATE()返回一个DATETIME值,如果字符串只包含日期或时间部分,则返回一个DATE或TIME值。如果从中提取的日期、时间或日期时间值不str合法,则STR_TO_DATE()返回NULL并产生警告。
Example:
例子:
SELECT STR_TO_DATE('15-Dec-09', '%d-%b-%y') AS date;
+------------+
| date |
+------------+
| 2009-12-15 |
+------------+
1 row in set (0.00 sec)
回答by Bob Stein
Here's a table of format %-codes used in DATE_FORMAT()and STR_TO_DATE().
这是DATE_FORMAT()和STR_TO_DATE() 中使用的格式 %-codes 表。
-----examples-for------
1999-12-31 2000-01-02
23:59:58.999 03:04:05 identical to
------------ ---------- -------------
%a Fri Sun LEFT(DAYNAME(d),3)
%b Dec Jan LEFT(MONTHNAME(d),3)
%c 12 1 MONTH(d)
%D 31st 2nd DAYOFMONTH(d)+st,nd,rd
%d 31 02 LPAD(DAYOFMONTH(d),0,2)
%e 31 2 DAYOFMONTH(d)
%f 999000 000000 LPAD(MICROSECOND(t),6,0)
%H 23 03 LPAD(HOUR(t),2,0)
%h 11 03
%I 11 03
%i 59 04 LPAD(MINUTE(t),2,0)
%j 365 002
%k 23 3 HOUR(t)
%l 11 3
%M December January MONTHNAME(d)
%m 12 01 LPAD(MONTH(d),2,0)
%p PM AM
%r 11:59:58 PM 03:04:05 AM
%S 58 05 LPAD(SECOND(t),2,0)
%s 58 05 LPAD(SECOND(t),2,0)
%T 23:59:58 03:04:05
%U 52 01 LPAD(WEEK(d,0),2,0)
%u 52 00 LPAD(WEEK(d,1),2,0)
%V 52 01 RIGHT(YEARWEEK(d,2),2)
%v 52 52 RIGHT(YEARWEEK(d,3),2)
%W Friday Sunday DAYNAME(d)
%w 5 0 DAYOFWEEK(d)-1
%X 1999 2000 LEFT(YEARWEEK(d,2),4)
%x 1999 1999 LEFT(YEARWEEK(d,3),4)
%Y 1999 2000 YEAR(d)
%y 99 00 RIGHT(YEAR(d),2)
%% % %
or
或者
%X%V 199952 200001 YEARWEEK(d,2)
%x%v 199952 199952 YEARWEEK(d,3)
By the way there are no %-codes for unpadded minutes or seconds:
顺便说一句,未填充的分钟或秒没有 % 代码:
59 4 MINUTE(t)
58 5 SECOND(t)
In action:
在行动:
'15-Dec-09' == DATE_FORMAT('2009-12-15', '%d-%b-%y')
'2009-12-15' == STR_TO_DATE('15-Dec-09', '%d-%b-%y')

