Question

I am working on a table that has two formats of dates stored in a field some are in mm/dd/yy and the newer entries are in yyyy/mm/dd like they should be.

I want to run an query like this

UPDATE table
   SET date_field = DATE_FORMAT(date_field, '%Y/%m/%d') 
 WHERE date_field = DATE_FORMAT(date_field, '%m/%d/%y')

But it is just not working out. One result that I got was that it was just taking the %m data and turning it into the %Y and really messing up the data.

Any thoughts?

Was it helpful?

Solution

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

OTHER TIPS

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top