Search code examples
phpvalidationdatetimerfc3339

Validate RFC3339 date-time using php


Any recommendations how to validate that a date-time is valid RFC3339?  I know I can convert it to unix time and then format it as valid RFC3339, but don't wish to do so and instead enforce that the correct format is provided.  http://mattallan.org/posts/rfc3339-date-time-validation/ suggests using regex, will only do as a last resort.  Thanks


Solution

  • DateTime has a predefined DaTeTime::RFC3339 format constant. Since createFromFormat returns false if it can't parse the date according to the provided format, you can use that check as your validator:

    validRFC3339Date("2018-01-29T20:36:01Z");
    validRFC3339Date("2018-01-29T20:36:01+00:00");
    
    validRFC3339Date("2018-01-22 20:36");
    validRFC3339Date("2018-09-28T16:00:05.000Z");
    
    function validRFC3339Date($date) {
        if (DateTime::createFromFormat(DateTime::RFC3339, $date) === FALSE) {
            echo "$date: Invalid RFC3339\n";
        } else {
            echo "$date: Valid RFC3339\n";
        }
    }