0

When I try to convert a string to a date in MYSQL, I'm getting weird results.

SELECT 
    '2017-06-20' d
    ,CAST('2017-06-20' as DATE) d1
    ,DATE_FORMAT('2017-06-20', '%Y-%m%-%d') d2 
    ,STR_TO_DATE('2017-06-20', '%Y-%m-%d') d3
    ,DATE('2017-06-20') d4

On my machine, d2 is the only correct date, i.e. it generates 2017-06-20. The rest, i.e. d1, d3 and d4, generate 06/19/2017. Why? I'm especially perplexed by STR_TO_DATE

Jacob H
  • 4,317
  • 2
  • 32
  • 39

1 Answers1

1

You are confused about data types. MySQL has built-in data types. It will recognize 'YYYY-MM-DD' as a string.

When the result of an expression is a string, it is put into the result set as-is.

When the result is a date/time, then it is shown based on your local settings.

So, DATE_FORMAT() is interpreting the first argument as a date and converting it to a string. That is what you get.

On the other hand, STR_TO_DATE() does what the name implies. It converts the first argument -- a string -- to a date. That is then presented based on your local settings.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786