There are numerous ways to print out dates and times, and many hours of programming are spent in converting dates from one format to another.
To do this in MySQL you use the STR_TO_DATE() function, which has two parameters. The first parameter is the time to be parsed and the second is the format of that time. Here is a simple example that converts one date format to a MySQL formatted date string.
SELECT STR_TO_DATE('[ 21/Apr/2009:07:14:50 +0100]', '[ %d/%b/%Y:%H:%i:%S +0100]');
This outputs 2009-04-21 07:14:50.
Using this function is quite intuitive and means that you can convert between time formats very easily. Here are a few more examples of this function.
- SELECT STR_TO_DATE('21/04/2009', '%d/%m/%Y'); // 2009-04-21
- SELECT STR_TO_DATE('04/21/2009', '%m/%d/%Y'); // 2009-04-21
- SELECT STR_TO_DATE('2009-04-21 14', '%Y-%m-%d %H'); // 2009-04-21 14:00:00
If you enter a date that can't be translated then you will get an error, take the following code that tries to convert a minute value of 87.
SELECT STR_TO_DATE('2009-04-21 14:87', '%Y-%m-%d %H:%i');
The following error message is returned.
Incorrect datetime value: '2009-04-21 14:87' for function str_to_date
This error can be quite easy to reproduce. For example, if you wanted to parse a time that was in 24 format, you would use the %H for hours. Using the %h value for hours will produce exactly this error.
The following table lists all of the different parameters that are involved in the date formatting features within MySQL. Use this to parse your own dates.
|%a||Abbreviated weekday name (Sun..Sat)|
|%b||Abbreviated month name (Jan..Dec)|
|%c||Month, numeric (0..12)|
|%D||Day of the month with English suffix (0th, 1st, 2nd, 3rd, ...)|
|%d||Day of the month, numeric (00..31)|
|%e||Day of the month, numeric (0..31)|
|%i||Minutes, numeric (00..59)|
|%j||Day of year (001..366)|
|%M||Month name (January..December)|
|%m||Month, numeric (00..12)|
|%p||AM or PM|
|%r||Time, 12-hour (hh:mm:ss followed by AM or PM)|
|%T||Time, 24-hour (hh:mm:ss)|
|%U||Week (00..53), where Sunday is the first day of the week|
|%u||Week (00..53), where Monday is the first day of the week|
|%V||Week (01..53), where Sunday is the first day of the week; used with %X|
|%v||Week (01..53), where Monday is the first day of the week; used with %x|
|%W||Weekday name (Sunday..Saturday)|
|%w||Day of the week (0=Sunday..6=Saturday)|
|%X||Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V|
|%x||Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v|
|%Y||Year, numeric, four digits|
|%y||Year, numeric (two digits)|
|%%||A literal % character|
|%x||x, for any x not listed above|
This function is really helpful for me. I've been searching for this and I'm very lucky to find this post. Thank you for sharing.
SET @@SESSION.sql_mode='NO_ZERO_DATE,NO_ZERO_IN_DATE';insert into test ('1','Sajjad',STR_TO_DATE('2009-04-21 14:87', '%Y-%m-%d %H:%i'))