5

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')");
1
  • 1
    try with DATE_FORMAT() Commented Feb 24, 2012 at 7:32

7 Answers 7

9

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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')");

Comments

2

Try this:

INSERT INTO table(date_field) VALUES(STR_TO_DATE('December 8, 2010','%M %d,%Y'));

Comments

1

Try it with DATE_FORMAT() function.

 mysql_query("UPDATE Table SET date=DATE_FORMAT(date,'%Y,%m,%d')");

Comments

1
  1. To display 2 digit year

    mysql_query("UPDATE Table SET date=DATE_FORMAT(date,'%y-%m-%d')");

  2. To display 4 digit year

    mysql_query("UPDATE Table SET date=DATE_FORMAT(date,'%Y-%m-%d')");

2 Comments

This query does not convert format... it is probably because the field is "tinytext" not DATE or TIMESTAMP.
you meant variable date is of varchar type??
1

I'd say you have to do this:

UPDATE table_name SET date = DATE_FORMAT('date', %Y-%m-%d);

Comments

0

If you are using my_sql with php, you can use date function

Comments

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.