I am reading some data from excel and import them to the db. But having a strange problem. Everything is ok except the date section. the code section is:
$dob = $cells[$i][6];
echo $dob.'<br>';
$timestamp = strtotime($dob);
echo 'time- '.$timestamp;
echo 'time2- '.strtotime('01-01-2000');exit;
and the output is:
01-01-2000
time- time2- 946677600
The value I used in the excel file is exactly the same 01-01-2000 as you can see from the output.
I don't understand why strtotime function can return a value for hardcoded string version but not with the variable read from excel file?
Thanks for any help.
Solution: In case someone faces the same problem this is how I handled it.
$dob_temp = $cells[$i][6];
$dob_numbers = preg_replace("/[^0-9]/","",$dob_temp);
$timestamp = strtotime(substr($dob_numbers,0,2).'-'.substr($dob_numbers,2,2).'-'.substr($dob_numbers,4,4));
$dob = date('Y-m-d', $timestamp);
It's likely that the string you retrieve from the excel file has some odd characters - for example a dash rather than a hyphen which trips up strtotime
.
Example:
<?php
$dob = '01―01―2000';
echo $dob.'<br>';
$timestamp = strtotime($dob);
echo 'time- '.$timestamp;
echo 'time2- '.strtotime('01-01-2000');exit;
You may want to clean up dates coming from the file or use something like DateTime::createFromFormat to pass a format which matches the contents of the string.