简体   繁体   中英

mysql convert date from mm-dd-yyyy to YYYY-MM-DD format

I want to convert given date from mm-dd-yyyy to YYYY-MM-DD format

I have tried following

SELECT DATE_FORMAT("09-02-2018",'YYYYMMDD')

SELECT DATE_FORMAT("09-02-2018", "%MM %dd %YY");

SELECT CURDATE("09-02-2018");

SELECT DATE_FORMAT("09-02-2018", "%Y-%m-%d")

It works fine for current date, but not for a given date.

You will need to use STR_TO_DATE function. From MySQL documentation:

It takes a string str and a format string format. STR_TO_DATE() returns a DATETIME value if the format string contains both date and time parts, or a DATE or TIME value if the string contains only date or time parts. If the date, time, or datetime value extracted from str is illegal, STR_TO_DATE() returns NULL and produces a warning.

The server scans str attempting to match format to it. The format string can contain literal characters and format specifiers beginning with %. Literal characters in format must match literally in str. Format specifiers in format must match a date or time part in str.

  • %m represents Month name as a numeric value (00 to 12)
  • %d represents Day of the month as a numeric value (01 to 31)
  • %Y represents Year as a numeric, 4-digit value

Since your input date is in mm-dd-yyyy format, we use %m-%d-%Y as the format here. Check the following code:

SELECT STR_TO_DATE('09-02-2018', '%m-%d-%Y');

The original format is not the MySQL format, so DATE_FORMAT won't work

You should do something like

SET @toconvert = '09-02-2018';
SELECT
    CAST(CONCAT(SUBSTR(@toconvert,7,4),'-',SUBSTR(@toconvert,4,2),'-',SUBSTR(@toconvert,1,2)) AS DATE);

Use STR_TO_DATE function to convert your string date to date type. For example:

SELECT STR_TO_DATE("09-02-2018", '%d-%m-%Y')

You can use the following syntax to get date in format.

DATE_FORMAT(STR_TO_DATE(myVal, '%d.%m.%y'), '%Y-%m-%d')

Thank You

使用STR_TO_DATE http://sqlfiddle.com/#!9/a6c585/71892

SELECT STR_TO_DATE("09-02-2018", '%d-%m-%Y')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM