Search code examples
phpdatedatetimeiso8601

How to recognise the 'T' character correctly within this ISO 8601 date in PHP


I have the following string with the 'T' seperator - how do change the $format var correctly to take into account the 'T' within the $datestring?

$datestring = '2018-12-30T11:30:00';
$format = 'Y-m-dG:i:s';
$date = DateTime::createFromFormat($format, $datestring);
var_dump($date); // currently returns false rather than an object

Solution

  • You can escape characters in the formats (\T):

    $datestring = '2018-12-30T11:30:00';
    $date = DateTime::createFromFormat('Y-m-d\TG:i:s', $datestring);
    
    var_dump($date);
    // object(DateTime)#1 (3) { ["date"]=> string(26) "2018-12-30 11:30:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/Berlin" }
    

    If you also need to validate the date you can use DateTime::getLastErrors:

    if (!empty(DateTime::getLastErrors()['warning_count'])) {
        echo 'Date <b>' . $datestring . '</b> is invalid.<br>';
    }
    

    Because dates like 2018-15-46T29:63:89 would return an object but aren't valid.