date_create_from_format does not give back expected result

后端 未结 2 512
时光取名叫无心
时光取名叫无心 2021-01-24 16:20

I just tried,

date_create_from_format(\'Ym\',\'201302\')

And I guess because it\'s the 29th today, it\'s actually giving me back March 1st.

相关标签:
2条回答
  • 2021-01-24 16:43

    TheWolf's solution seems to work perfectly, but here's an alternative I started writing anyway:

    function CompactStrToTime($str) {
        $year = strlen($str)>=4 ? substr($str,0,4) : date('Y');
        $month = strlen($str)>=6 ? substr($str,4,2) : 1;
        $day = strlen($str)>=8 ? substr($str,6,2) : 1;
        $hour = strlen($str)>=10 ? substr($str,8,2) : 0;
        $min = strlen($str)>=12 ? substr($str,10,2) : 0;
        $sec = strlen($str)>=14 ? substr($str,12,2) : 0;
        return mktime($hour,$min,$sec,$month,$day,$year);
    }
    
    0 讨论(0)
  • 2021-01-24 16:55

    If format does not contain the character ! then portions of the generated time which are not specified in format will be set to the current system time.

    If format contains the character !, then portions of the generated time not provided in format, as well as values to the left-hand side of the !, will be set to corresponding values from the Unix epoch.

    The Unix epoch is 1970-01-01 00:00:00 UTC. (DateTime Manual)

    So, adding a ! at the beginning of your format string should fix your problem.

    0 讨论(0)
提交回复
热议问题