2

I have to import a database from an existing site into the new site which we have made. The dob fields stored in the earlier db is creating problem. There dob format is mm/dd/yy or mm/dd/yyyy, whereas we need to save in Y-m-d format.

I m using this code,which works fine for date

$case_contact_dateval = '04/11/81';

and gives me date 1981-04-11, which is correct. Whereas in

$case_contact_dataval = '03/22/67';
$date = DateTime::createFromFormat('m/d/y',$case_contact_dataval);
echo $date = $date->format('Y-m-d');

Some other dates are

 $case_contact_dataval = '03/22/67';
 $case_contact_dataval = '07/05/40';
 $case_contact_dataval = '01/25/59';
 $case_contact_dataval = '03/09/58';

I get date as 2067-03-22, which is wrong as all these dates are date of birth. I m using php 5.4.6 on ubuntu. I have many like these dates for which the same code works fine and for some wrong. Can't get a soln... Please advice.

  • Prior to PHP 5.1.0, this might have the answer you are looking for: http://stackoverflow.com/questions/2871264/using-strtotime-for-dates-before-1970#answer-2872094 – Adil Abbas May 23 '14 at 10:53

2 Answers2

2

DateTime treats any two-digit year under 70 as being in the 21st century.

You'll have to transform the data instead of trying to create dates. For example

$case_contact_dataval = '03/22/67';
$threshold = date('y'); // current two digit year
list($month, $day, $year) = sscanf($case_contact_dataval, '%d/%d/%d');
$date = sprintf('%02d%02d-%02d-%02d',
    $year > $threshold ? 19 : 20, $year, $month, $day);

Demo here ~ https://eval.in/155942

I even threw in a more current date to show you how it handles that.

Phil
  • 157,677
  • 23
  • 242
  • 245
-2

Birthday can't be in future. Add '19' if birthday > current year

$case_contact_dateval = '04/11/67';
if (substr($case_contact_dateval, -2) > date('y')) {
    $case_contact_dateval = substr($case_contact_dateval, 0, -2) . '19' . substr($case_contact_dateval, -2);
}
$date = \DateTime::createFromFormat('m/d/Y', $case_contact_dateval);
echo $date->format('Y-m-d');
newage
  • 899
  • 7
  • 18
  • I don't understand why this is down voted. It isn't the best code I've ever seen, but it [seems to work](http://3v4l.org/KMjZv). – vascowhite May 25 '14 at 06:37