dongwen7187 2015-12-23 04:21
浏览 137
已采纳

函数来反转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

  • 写回答

1条回答 默认 最新

  • doutuo6689 2015-12-23 05:28
    关注

    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")."
    ";
        }
    

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器