Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql change date format

Tags:

mysql

I have a date field (tinytext) holding date information in format of "dd-mm-yy" e.g 07-01-90. Using a mysql query I want to change it to yyyy-mm-dd date format. I tried the code below but nothing happens.

mysql_query("UPDATE Table SET date=STR_TO_DATE('date','%Y,%m,%d')");
like image 981
mustafa Avatar asked Feb 24 '12 07:02

mustafa


2 Answers

You're using the correct function STR_TO_DATE(str,format) to achieve the goal, but you're making two mistakes:

  1. In your query the format argument does not match the string expression format. You said it's in dd-mm-yy format while you passed %Y,%m,%d (comma separated) to the format argument. The query will return a "incorrect datetime value" error. You should use %d-%m-%Y.
  2. You can't change data type of a column on the fly, by setting different type of the value being passed. You have to first update the values and then change data type for column.

So, summarizing:

mysql_query("UPDATE `Table` SET `date` = STR_TO_DATE(`date`, '%d-%m-%Y')");
mysql_query("ALTER TABLE `Table` CHANGE COLUMN `date` `date` DATE");

Additionally, consider switching to the recommended PDO extension in place of old and slowly deprecated mysql extension.

like image 110
Taz Avatar answered Oct 10 '22 04:10

Taz


Error in your query

is STR_TO_DATE(date, '%Y-%m-%d')

mysql_query("UPDATE Table SET date=STR_TO_DATE(date,'%Y-%m-%d')");
like image 21
Naveen Kumar Avatar answered Oct 10 '22 03:10

Naveen Kumar