59

I have a bunch of records with dates formatted as a string such as '04/17/2009'

I want to convert them to a mysql datetime field

I plan to use a foreach loop to read the old date value and insert the newly formatted value into a new field in each record

what would be the best way to convert that string...I thought php might have a way to do it automatically?

thanks

6 Answers 6

98

First, convert the string into a timestamp:

$timestamp = strtotime($string);

Then do a

date("Y-m-d H:i:s", $timestamp);
Sign up to request clarification or add additional context in comments.

2 Comments

or do it at once: date("Y-m-d H:i:s", strtotime($string));
Date returns a string. Is this acceptable?
25

If these strings are currently in the db, you can skip php by using mysql's STR_TO_DATE() function.

I assume the strings use a format like month/day/year where month and day are always 2 digits, and year is 4 digits.

UPDATE some_table
   SET new_column = STR_TO_DATE(old_column, '%m/%d/%Y')

You can support other date formats by using other format specifiers.

3 Comments

this would be a great way to go, too bad my db skills aren't up to the task
+1. Had to convert 3000 fake names exported by fakenamegenerator.com, and one field was named "birthday". Had every field stored in MM/DD/YYYY format as a VARCHAR field. This answer helped immensely.
must be the answer
8

Use DateTime::createFromFormat like this :

$date = DateTime::createFromFormat('m/d/Y H:i:s', $input_string.' 00:00:00');
$mysql_date_string = $date->format('Y-m-d H:i:s');

You can adapt this to any input format, whereas strtotime() will assume you're using the US date format if you use /, even if you're not.

The added 00:00:00 is because createFromFormat will use the current date to fill missing data, ie : it will take the current hour:min:sec and not 00:00:00 if you don't precise it.

1 Comment

Nice option for dates pre 1970
1
$time = strtotime($oldtime);

Then use date() to put it into the correct format.

Comments

0

I assume we are talking about doing this in Bash?

I like to use sed to load the date values into an array so I can break down each field and do whatever I want with it. The following example assumes and input format of mm/dd/yyyy...

DATE=$2
DATE_ARRAY=(`echo $DATE | sed -e 's/\// /g'`)
MONTH=(`echo ${DATE_ARRAY[0]}`)
DAY=(`echo ${DATE_ARRAY[1]}`)
YEAR=(`echo ${DATE_ARRAY[2]}`)
LOAD_DATE=$YEAR$MONTH$DAY

you also may want to read up on the date command in linux. It can be very useful: http://unixhelp.ed.ac.uk/CGI/man-cgi?date

Hope that helps... :)

-Ryan

1 Comment

It's PHP/MySQL. You check the tags once in a while ;)
0
SELECT *
FROM table_name
WHERE CONCAT( SUBSTRING(json_date, 11, 4 ) ,  '-', SUBSTRING( json_date, 7, 2 ) ,  '-', SUBSTRING( json_date, 3, 2 ) ) >= NOW();

json_date ["05/11/2011"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.