how to convert a string to date in mysql?

后端 未结 5 485
谎友^
谎友^ 2020-11-22 07:26

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

5条回答
  •  情话喂你
    2020-11-22 07:39

    The following illustrates the syntax of the STR_TO_DATE() function:

    STR_TO_DATE(str,fmt);
    

    The STR_TO_DATE() converts the str string into a date value based on the fmt format string. The STR_TO_DATE() function may return a DATE , TIME, or DATETIME value based on the input and format strings. If the input string is illegal, the STR_TO_DATE() function returns NULL.

    The following statement converts a string into a DATE value.

    SELECT STR_TO_DATE('21,5,2013','%d,%m,%Y');
    

    Based on the format string ‘%d, %m, %Y’, the STR_TO_DATE() function scans the ‘21,5,2013’ input string.

    • First, it attempts to find a match for the %d format specifier, which is a day of the month (01…31), in the input string. Because the number 21 matches with the %d specifier, the function takes 21 as the day value.
    • Second, because the comma (,) literal character in the format string matches with the comma in the input string, the function continues to check the second format specifier %m , which is a month (01…12), and finds that the number 5 matches with the %m format specifier. It takes the number 5 as the month value.
    • Third, after matching the second comma (,), the STR_TO_DATE() function keeps finding a match for the third format specifier %Y , which is four-digit year e.g., 2012,2013, etc., and it takes the number 2013 as the year value.

    The STR_TO_DATE() function ignores extra characters at the end of the input string when it parses the input string based on the format string. See the following example:

    SELECT STR_TO_DATE('21,5,2013 extra characters','%d,%m,%Y');
    

    More Details : Reference

提交回复
热议问题