0

i have a column with 'char' data type with two format records like this,

my_char_column
2030-05-12
2/8/2017
2012-12-13

the problem i want to change type data to 'date' with 'Y-m-d' format like this,

my_char_column_new
2030-05-12
2017-08-02
2012-12-13

i have tried to use this query but doesn't work

UPDATE my_table SET my_char_column = DATE_FORMAT(my_char_column,'%Y-%m-%d') where my_char_column LIKE'%/%'
2
  • Does all date only have these two formats? Commented Nov 24, 2017 at 7:43
  • yes, just two formats Commented Nov 24, 2017 at 11:39

1 Answer 1

2

This is a similar answer: https://stackoverflow.com/a/12734990/8364246

Here is my way: What you need here is some kind of condition check that can choose between two possibilities, IFNULL will serve that purpose. DATE_FORMAT(STR_TO_DATE(my_char_column, '%Y-%m-%d') this convert "2030-05-12" this type of date, while DATE_FORMAT(STR_TO_DATE(my_char_column, '%d/%m/%Y') will convert "2/8/2017" this type of date to the format you want i.e. %Y-%m-%d.

select IFNULL(DATE_FORMAT(STR_TO_DATE(my_char_column, '%Y-%m-%d'), '%Y-%m-%d'), DATE_FORMAT(STR_TO_DATE(my_char_column, '%d/%m/%Y'), '%Y-%m-%d')) from your_table;
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for your answer, but that's not change my format date. are you have idea to select only like '2/8/2017' format ? i will change to 'y-m-d' format first before change the type data.
You can use a script in php or python to read columns one by one, then split the columns with '/', if the size of array thus created is more than one, the means the date is of "2/8/2017" format. Then you can combine it back to "2017-8-2" format. Then all the columns will be converted to same format. Then you can directly use STR_TO_DATE() function to convert string to date, or you can use your script only to convert string to date and insert back to table.
yes, i was thinking about that. I just try to find more eficient way to do that because i have 27530 record to change it. Thnks for your time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.