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...
CodePudding user response:
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"
}
CodePudding user response:
To parse a date string into a DateTimeImmutable object, you can use the createFromFormat function as you already did but you have to change the input parameter like so:
Here's an example of how you can do this:
$date_string = '2018-07-17T17:34:08.167';
$format = 'Y-m-d\TH:i:s.v';
$date = DateTimeImmutable::createFromFormat($format, $date_string);
echo $date->format('Y-m-d H:i:s.v');
// Outputs "2018-07-17 17:34:08.167"
Note that the v
format specifier represents the milliseconds.