Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function to reverse DateTime::createFromFormat / date_create_from_format

I'm accidently made mistake by convert string to date with wrong format (month to date). So here's what I have done:

DateTime::createFromFormat('d/m/Y', '12/26/1987')->format("d/m/Y");

so it is outputing wrong date, from 12/26/1987 became 10/02/1989 and I have save a lot of the wrong date to the database. Is there any reverse method or enlightment to get the original date before it has been converted.

thank in advance

like image 526
moc4yu Avatar asked Jul 07 '26 09:07

moc4yu


1 Answers

You lost information when you converted your date (1-31) into a month (1-12), so based on what I've seen, all of your improperly formatted dates can be one of 2-3 other dates. The following code prints out what the other possible dates are if you give it one of your wrong dates. I think that's about all you can do:

    $date = DateTime::createFromFormat('d/m/Y', '12/26/1987');

    $possible_dates = array();
    $remainder_start = 0;
    $days_in_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    while ($remainder_start <= $days_in_month[intval($date->format("m")])
    {
        $possible_dates[] = DateTime::createFromFormat("m/d/Y", $date->format("d")."/".(intval($date->format("m"))+$remainder_start)."/".(intval($date->format("Y"))-($remainder_start/12)));
        $remainder_start += 12;
    }

    foreach ($possible_dates as $d)
    {
        echo $d->format("m/d/Y")."\n";
    }

This will print out 12/02/1989 12/14/1988 12/26/1987

Your month will always be right even in the wrong date since you put that in the day position, but your years and days will be one of several combinations.

If the day in the original date was the 12th of the month or sooner your "wrong" date is actually still correct.

like image 62
Chris Trudeau Avatar answered Jul 10 '26 00:07

Chris Trudeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!