Chechi
Chechi

Reputation: 13

MySQL: extracting date from string

Is it possible to get the date in mysql from this string: Thu Mar 10 005758 EST 2016 ? I'd like to get the date in mm/dd/yy format.

Upvotes: 0

Views: 472

Answers (1)

Dylan Su
Dylan Su

Reputation: 6065

Use STR_TO_DATE() to convert the original string to a date:

mysql> SELECT STR_TO_DATE('Thu Mar 10 005758 EST 2016', '%a %b %e %H%i%s EST %Y');
+---------------------------------------------------------------------+
| STR_TO_DATE('Thu Mar 10 005758 EST 2016', '%a %b %e %H%i%s EST %Y') |
+---------------------------------------------------------------------+
| 2016-03-10 00:57:58                                                 |
+---------------------------------------------------------------------+
1 row in set (0.00 sec)

Then use DATE_FORMAT() to format it as you wanted 'mm/dd/yy':

mysql> SELECT DATE_FORMAT( STR_TO_DATE('Thu Mar 10 005758 EST 2016', '%a %b %e %H%i%s EST %Y'), '%m/%d/%y');
+-----------------------------------------------------------------------------------------------+
| DATE_FORMAT( STR_TO_DATE('Thu Mar 10 005758 EST 2016', '%a %b %e %H%i%s EST %Y'), '%m/%d/%y') |
+-----------------------------------------------------------------------------------------------+
| 03/10/16                                                                                      |
+-----------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

Upvotes: 3

Related Questions