how to convert a string to date in mysql?

Joseph Lafuente picture Joseph Lafuente · Mar 5, 2011 · Viewed 390.4k times · Source

I have a string column which acts as a date and I want to select it as a date.

Is it possible?

My sample data format would be; month/day/year -> 12/31/2011

Answer

bluefoot picture bluefoot · Mar 5, 2011

As was told at MySQL Using a string column with date text as a date field, you can do

SELECT  STR_TO_DATE(yourdatefield, '%m/%d/%Y')
FROM    yourtable

You can also handle these date strings in WHERE clauses. For example

SELECT whatever
  FROM yourtable
 WHERE STR_TO_DATE(yourdatefield, '%m/%d/%Y') > CURDATE() - INTERVAL 7 DAY

You can handle all kinds of date/time layouts this way. Please refer to the format specifiers for the DATE_FORMAT() function to see what you can put into the second parameter of STR_TO_DATE().