PHP validate ISO 8601 date string

后端 未结 5 1587
半阙折子戏
半阙折子戏 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:47

    Edit: By far the easiest method is to simply try to create a DateTime object using the string, eg

    $dt = new DateTime($dateTimeString);
    

    If the DateTime constructor cannot parse the string, it will throw an exception, eg

    DateTime::__construct(): Failed to parse time string (2011-10-02T23:25:72Z) at position 18 (2): Unexpected character

    Note that if you leave off the time zone designator, it will use the configured default timezone.

    Second easiest method is to use a regular expression. Something like this aught to cover it

    if (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(Z|(\+|-)\d{2}(:?\d{2})?)$/', $dateString, $parts)) {
        // valid string format, can now check parts
    
        $year  = $parts[1];
        $month = $parts[2];
        $day   = $parts[3];
    
        // etc
    }
    

提交回复
热议问题