Search code examples
phpdatetimedatetime-format

How do I create from format an ISO 8601 date with milliseconds in PHP?


I am trying to parse the date 2018-07-17T17:34:08.167 into a DateTimeImmutable object in my code, which I tried to do with:

\DateTimeImmutable::createFromFormat('c', $s);

However, because of the milliseconds present and the lack of the time zone, PHP returns false for this.

I then tried to create it by defining the format myself, but the problem is that T is used as a timezone abbreviation.

\DateTimeImmutable::createFromFormat('YYYY-mm-ddTHH:ii:ss.v', $s);
\DateTimeImmutable::createFromFormat('YYYY-mm-dd\\THH:ii:ss.v', $s);

I read this answer and tried wildcards, but no dice.

\DateTimeImmutable::createFromFormat('YYYY-mm-dd*HH:ii:ss.v', $s);

Anyone know how I can get this to parse?

EDIT: That moment when you spend a whole week coding in C# and then forget how to format in PHP...


Solution

  • You don't have to use 4 times Y (YYYY), because Y represent year in 4 digits. Same for other "time-markers".

    $s='2018-07-17T17:34:08.167';
    var_dump(\DateTimeImmutable::createFromFormat('Y-m-d\TH:i:s.v', $s));
    

    Output:

    object(DateTimeImmutable)#1 (3) {
      ["date"]=>
      string(26) "2018-07-17 17:34:08.167000"
      ["timezone_type"]=>
      int(3)
      ["timezone"]=>
      string(16) "Europe/Paris"
    }