1

Hi I am trying to convert dd-mm-yy to yy-mm-dd in mysql but I'm getting wrong date as below :

 query :  select STR_TO_DATE('01-09-2018','%Y-%m-%d')
   result:  2001-09-20

Please help me to solve this issue.

Kiran Kumar
  • 167
  • 1
  • 2
  • 13

4 Answers4

2

Try below: format string is wrong in your case

select STR_TO_DATE('01-09-2018','%d-%m-%Y')

Output:

'2018-09-01'
Fahmi
  • 37,315
  • 5
  • 22
  • 31
2

You need to use STR_TO_DATE function in the right way. It takes a string str and a format string format. Format pattern has to match your input str. In your case, you had dd-mm-yy has input, so you have to use matching format, that is, %d-%m-%Y

Try the following:

select STR_TO_DATE('01-09-2018','%d-%m-%Y')

Additional Details:

  • %d Day of the month as a numeric value (01 to 31)
  • %m Month name as a numeric value (00 to 12)
  • %Y Year as a numeric, 4-digit value
  • Note that STR_TO_DATE function will always return in MySQL standard date format, which is yyyy-mm-dd (if input is date only).
  • If you want to convert into some other format, then you will need to use a combination of STR_TO_DATE alongwith DATE_FORMAT function.
Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57
1

Simply put, you're confusing the parameters. In your example you provide %Y-%m-%d which is your expected output. The second parameter of STR_TO_DATE should be the format of the string you're supplying:

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

The default MySQL datestring is: %Y-%m-%d, which is what is yielded from the query above:

2018-09-01

See the following SQL fiddle: https://www.db-fiddle.com/f/2411rcvjH6dKZYLzxkii39/0

Blue
  • 22,608
  • 7
  • 62
  • 92
0

It seems you wrote the parsing parameters wrong... the should point to the string's parameters

SELECT
    STR_TO_DATE('01-09-2018','%d-%m-%Y');
Guy Louzon
  • 1,175
  • 9
  • 19