I have a script which is reading values from an excel sheet and inserting them into an sql table. My problem is when the script reads in some of the date fields it is setting them to a default value :
I have noticed that this is happening when it comes across a date where the ‘day’ is greater than 12 :
13/05/2012 18:52:33 (dd-mm-yyyy hh-mm-ss)
I thought this may be due to the script thinking that this is the month field (i.e american format) and it sees it as an invalid value, so I set the default timezone to my own hoping it may resolve the problem but it made no difference.
Here is an example of what my code is doing:
Excel field value :
$start_time = $data->val($x,5); echo $start_time = date("Y-m-d H:i:s", strtotime($start_time));
This is the exact format I am looking for (except for the fact that the day and month fields are switched around i.e american date format) but it doesnt work for the type of dates I mentioned above.
DateTime object might be your solution. you can do
$dt = DateTime::createFromFormat("d/m/Y H:i:s", $data->val($x,5);); echo $dt->format('Y-m-d H:i:s');
and select the format you want.
This should do the job for you:
// example datetime $orig_date = '13/05/2012 18:52:33'; // split date & time into array $date_time = preg_split('/\s+/', $orig_date); // date in array formated as ddmmyyyy list($d, $m, $y) = preg_split('/\//', $date_time); // date re-formated as yyyy-mm-dd for MySQL $new_date = sprintf('%4d-%02d-%02d', $y, $m, $d); // And add time on again with a space for MySQL datetime format echo $new_date.' '.$date_time;
From the notes on
strtotime(), the function assumes that dates seperated by
m/d/y and dates seperated by a
You could either replace the slashes in your date string, or if you’re using 5.3 or higher, use
date_parse_from_format(), and provide the format directly.
And as mentioned by jaudette you can also use
DateTime::createFromFormat(), and get an object instead of a timestamp.