Converting between illogically formatted dates (changing /slash/ to -dash- )
I am rebuilding a web application from an old one with many inconsistencies. I have to migrate all the data over from the old database to our new structure.
In the old database, dates were stored in the MySQL DB as VARCHAR. We are based in the UK, so dates were written in the format DD/MM/YYYY. I need to convert these dates to MySQL's native DATE() format.
Problem is this - PHP defaults to assuming the dates are in 'American' format (MM/DD/YYYY) because they were originally split with / rather than - - and - forces PHP to assume they are 'European' format.
I am doing this so far to convert them:
$start_date = date('Y-m-d', strtotime($query->row('startdate')));
Where $query->row('startdate') is the column in the old database which was storing the dates. Problem is, I need to first switch all the 21/03/1994s to 21-03-1994.
How can I do this?
$start_date = date('Y-m-d', strtotime(str_replace('/', '-', $query->row('startdate'))));
Or better yet - just change the data in the database:
UPDATE `table` SET `startdate` = REPLACE(`startdate`, '/', '-');
... and then convert the field to type DATE.
---- EDIT ----
Actually, Col. Shrapnel has a point ... I'd overlooked the fact that the date needs reversing as well so it's YYYY-MM-DD; assuming the original date is in the format DD/MM/YYYY a better query might be something like:
UPDATE `table` SET `date` = CONCAT(SUBSTRING(`date`, 7), '-', SUBSTRING(`date`, 4, 2), '-', SUBSTRING(`date`, 1, 2))
Which will reverse the component parts into a string that can be converted to a DATE ... it won't quite work if the original date string doesn't use leading zeroes 1/6/2011 for instance... would need to do something a little cleverer in that case.