Search code examples
phpdatedate-conversion

PHP get time from personal identity number under 1970


I have problem, I can't get time from personal identity number under 1970, I need to solve that, but using time. My function looks like. I don't know which way I can go. Thanks!

    function getBirthDayFromRd($rd){

$day = substr($rd,4,2);
$month = substr($rd, 2,2);
$year = substr($rd, 0,2);

if($month>=51 and $month<=62){ 
$month = $month - 50;
    }

$time = strtotime($day.".".$month.".".$year);

return date("d.m.Y", $time);


}

Solution

  • strtotime() fails due to its being tied to the Unix epoch which does not support dates prior to 1970. Just use DateTime which can handle pre-1970 dates and convert dates easily:

    function getBirthDayFromRd($rd){
        $date = DateTime::createFromFormat('ymd',$rd);
        if($date->format('Y') > date("Y")) {
             $date->modify('-100 years');
        }
        return $date->format('d.m.Y');
    }
    

    DateTime::createFromFormat() parses your date and creates the DateTime object. Then we just call DateTime::format() to format it in the desired format.

    update

    Just fixed a bug where pre-1970 dates were shown 100 years in the future.

    Demo