MySQL | STR_TO_DATE method
Start your free 7-days trial now!
MySQL's STR_TO_DATE(~)
method will return a date, time or datetime value from a string and its format.
Parameters
1. string
| string
The string to be converted to a date, time or datetime.
2. format
| string
The format of the string argument.
Return value
A date, time or datetime based on the input string.
Examples
Basic usage
To return a date value from the string 'July 5 2020'
:
SELECT STR_TO_DATE('July 5 2020','%M %d %Y');
+---------------------------------------+| STR_TO_DATE('July 5 2020','%M %d %Y') |+---------------------------------------+| 2020-07-05 |+---------------------------------------+
If the string does not match the format provided NULL
is returned:
SELECT STR_TO_DATE('July 5, 2020','%m %d,%Y');
+----------------------------------------+| STR_TO_DATE('July 5, 2020','%m %d,%Y') |+----------------------------------------+| NULL |+----------------------------------------+
Here, the format %m
means we are expecting a month number rather than month name, which is why NULL
is returned.
Correcting the above string to meet the '%m %d,%Y'
format:
SELECT STR_TO_DATE('07 5, 2020','%m %d,%Y');
+--------------------------------------+| STR_TO_DATE('07 5, 2020','%m %d,%Y') |+--------------------------------------+| 2020-07-05 |+--------------------------------------+
List of formatting types
Below is a table with a list of valid formatting types:
Specifier | Description |
---|---|
| Abbreviated weekday name (Sun..Sat) |
| Abbreviated month name (Jan..Dec) |
| Month, numeric (0..12) |
| Day of the month with English suffix (0th, 1st, 2nd, 3rd, …) |
| Day of the month, numeric (00..31) |
| Day of the month, numeric (0..31) |
| Microseconds (000000..999999) |
| Hour (00..23) |
| Hour (01..12) |
| Hour (01..12) |
| Minutes, numeric (00..59) |
| Day of year (001..366) |
| Hour (0..23) |
| Hour (1..12) |
| Month name (January..December) |
| Month, numeric (00..12) |
| AM or PM |
| Time, 12-hour (hh:mm:ss followed by AM or PM) |
| Seconds (00..59) |
| Seconds (00..59) |
| Time, 24-hour (hh:mm:ss) |
| Week (00..53), where Sunday is the first day of the week; WEEK() mode 0 |
| Week (00..53), where Monday is the first day of the week; WEEK() mode 1 |
Week (01..53), where Sunday is the first day of the week; WEEK() mode 2; used with %X | |
| Week (01..53), where Monday is the first day of the week; WEEK() mode 3; used with %x |
| Weekday name (Sunday..Saturday) |
| Day of the week (0=Sunday..6=Saturday) |
| Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V |
| Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v |
| Year, numeric, four digits |
| Year, numeric (two digits) |
A literal % character |