Search code examples
phpdatephp-carboniso8601

ISO 8601 parsing validation in Carbon


I am passing a date to my backend through ajax. The date is in ISO 8601 format and in UTC (E.G. 2017-07-04T23:21:37.000000Z). I am going to pass this string to create a carbon instance. Is there a way for carbon to throw an exception if the string I am passing is not ISO 8601 format? Basically I am looking for a function like

moment("2017-07-04T23:21:37.000000Z");

for momentjs or

parseISO("2017-07-04T23:21:37.000000Z");

for date-fns. The Carbon::parse method accept many accepted format so not good in my use case.


Solution

  • You can use Carbon::createFromFormat. Carbon is an extension of DateTime. I show it with DateTime, so it's reproducible for everyone.

    $strISO8601 = "2017-07-04T23:21:37.000000Z";
    $format = "Y-m-d\TH:i:s.uO";
    $dateTime = DateTime::createFromFormat($format, $strISO8601);
    

    If the format is not correct the result is false.

    From the Carbon Doc:

    Carbon::createFromFormat() is a wrapper for the base php function DateTime::createFromFormat. The difference being again the $tz argument can be a DateTimeZone instance or a string timezone value. Also, if there are errors with the format this function will call the DateTime::getLastErrors() method and then throw a InvalidArgumentException with the errors as the message.