PHP validate ISO 8601 date string

后端 未结 5 1581
半阙折子戏
半阙折子戏 2020-12-15 06:02

How do you validate ISO 8601 date string (ex: 2011-10-02T23:25:42Z).

I know that there are several possible representations of ISO 8601 dates, but I\'m only interest

5条回答
  •  星月不相逢
    2020-12-15 06:42

    I want to share my lightweight solution. It is not ideal, but might be helpful for someone.

    function validISO8601Date($value)
    {
        if (!is_string($value)) {
            return false;
        }
    
        $dateTime = \DateTime::createFromFormat(\DateTime::ISO8601, $value);
    
        if ($dateTime) {
            return $dateTime->format(\DateTime::ISO8601) === $value;
        }
    
        return false;
    }
    

    Atention!

    Some valid ISO8601 dates will fail Look at the list below

    NOT VALID  --> '' // Correct
    NOT VALID  --> 'string' // Correct
    VALID      --> '2000-01-01T01:00:00+1200' // This is the only format function returns as valid
    NOT VALID  --> '2015-01 first' // Correct
    NOT VALID  --> '2000-01-01T01:00:00Z' // Must be valid!
    NOT VALID  --> '2000-01-01T01:00:00+01' // Must be valid!
    

提交回复
热议问题