Home » excel » excel – PHP strtotime() setting date to default

excel – PHP strtotime() setting date to default

Posted by: admin May 14, 2020 Leave a comment


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 : 1970-01-01 01:00:00

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. date_default_timezone_set('Europe/Dublin');

Here is an example of what my code is doing:

Excel field value :

01/05/2012 18:32:45


$start_time  = $data->val($x,5);
echo $start_time = date("Y-m-d H:i:s", strtotime($start_time));


2012-01-05 18:32:45

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.

How to&Answers:

Using a 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[0]);
// 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[1];


From the notes on strtotime(), the function assumes that dates seperated by / are m/d/y and dates seperated by a - are d-m-y.

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.