Convert string with different format to date

試著忘記壹切 提交于 2019-12-01 00:43:37

There's a trick for detecting a valid date on the man page. You can use it to determine whether a STR_TO_DATE format worked.

select foo,
    case when length(date(str_to_date(foo,"%Y-%m-%d %H:%i:%S"))) is not null then str_to_date(foo,"%Y-%m-%d %H:%i:%S")
        when length(date(str_to_date(foo,"%b %d %Y %h:%i%p"))) is not null then str_to_date(foo,"%b %d %Y %h:%i%p")
    end as newdate
from my_table

Put one format for everyone you're expecting. Test like crazy.

Good luck.

(Oh, and congrats for trying to cleanup a bad schema!)

I would try to do this using a server side language, perhaps PHP and use strotime to generate a pretty date.

Otherwise, the only other option I see is to start writing CASEs to read possible formats, and output using DATE_FORMAT. Perhaps something like:

Pseudo-code (for case may 24 1983 12:00AM)

CASE
    WHEN col (after first space is some digit) 
        AND (after second space is 4 digits)
        AND (after third space has 'AM' or 'PM')
    THEN
        DATE_FORMAT(col, '%....')

You can also trying using REGEXP to for pattern matching.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!