updating a date format in mysql

ぐ巨炮叔叔 提交于 2019-11-29 04:51:35

You want to use STR_TO_DATE function, not DATE_FORMAT. Plus, I assume you only want to update the misformed dates, so I guess you could do this :

UPDATE your_table
SET date_field = DATE(STR_TO_DATE(date_field, '%m/%d/%Y'))
WHERE DATE(STR_TO_DATE(date_field, '%m/%d/%Y')) <> '0000-00-00';

P.S. Tables contain columns, not fields. And you shouldn't use a string type to hold your dates, but the DATE type

You want to use STR_TO_DATE to first convert the incorrect string to a real date object, then use DATE_FORMAT to turn it back into a string of the format you want.

Also, your WHERE condition won't work like that. You should be looking for strings of the wrong format using LIKE.

UPDATE your_table SET date_field =
    DATE_FORMAT(STR_TO_DATE(date_field, '%m/%d/%y'), '%Y/%m/%d') 
WHERE date_field LIKE '__/__/____'

Thoughts? Ah yes, three actually:

  • don't reinvent the wheel. Yes, yes, I know it's tempting to do from scratch what only a million of people have invented before (no sarcasm intended), but MySQL has a good, efficient, and usable DATE format, use that; only do the formatting on the input/output. That lets you avoid these kind of mixups of data (the date itself) and presentation (date format).

  • As for the data, restore the known-good backup (you have backups, right?) - in the general case, there's no fool-proof way to tell unconverted y/m/d from already-converted m/d/y and the dates are f***ed for any practical purposes. (especially not in 2010 - e.g. 08/10/09 can mean several valid dates).

  • Also, what kind of idea is it to only store 2 digits of the date? That's exactly the kind of short-sighted penny-pinching that has brought about the time- and money-sink that was Y2K. (avoided if you'd store the date, y'know, in a date format).

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