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.

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分