Parse date in MySQL

user157195 picture user157195 · Jul 21, 2010 · Viewed 50.9k times · Source

How to convert the following into date for insertion/update into a TIMESTAMP or DATE field in MySQL?

'15-Dec-09'

DATE_FORMAT() is used to format date, but not the other way around.

Answer

Daniel Vassallo picture Daniel Vassallo · Jul 21, 2010

You may want to use the STR_TO_DATE() function. It's the inverse of the DATE_FORMAT() function.

STR_TO_DATE(str,format)

This is the inverse of the DATE_FORMAT() function. It takes a string str and a format string format. STR_TO_DATE() returns a DATETIME value if the format string contains both date and time parts, or a DATE or TIME value if the string contains only date or time parts. If the date, time, or datetime value extracted from str is illegal, STR_TO_DATE() returns NULL and produces a warning.

Example:

SELECT STR_TO_DATE('15-Dec-09', '%d-%b-%y') AS date;
+------------+
| date       |
+------------+
| 2009-12-15 |
+------------+
1 row in set (0.00 sec)