DateTime::createFromFormat in PHP < 5.3.0

后端 未结 5 507
甜味超标
甜味超标 2021-01-20 04:06

I\'m looking for a function identical to DateTime::createFromFormat but I need it to work in an environment running a version of PHP which is older than v5.3. Basically I ne

5条回答
  •  盖世英雄少女心
    2021-01-20 04:15

    For PHP version prior to 5.3 I use this function bellow to get DateTime object form strings formated as 'DD.MM.YYYY'.

    function ParseForDateTimeValue ($strText)
    {
        if ($strText != "")
        {
            if (ereg("^([0-9]{1,2})[/\.]\s*([0-9]{1,2})[/\.]\s*([0-9]{2,4})$",$strText,$arr_parts)) {
    
                $month = ltrim($arr_parts[2], '0');
                $day = ltrim($arr_parts[1], '0');
                $year = $arr_parts[3];
    
                if (checkdate($month, $day, $year)) {
                   return new DateTime(date('Y-m-d H:i:s', mktime(0, 0, 0, $month, $day, $year));
                }
            }
        }
        return NULL;
    }
    
    • First validate if input is correct.
    • Then extract month, day and year
    • Use checkdate to validate the date.
    • Convert it to timestamp and pass it to contructor of DateTime and return it.

提交回复
热议问题