I want to convert this date-time string 2022-09-30T21:39:25.220185674Z
to yyyy-mm-dd hh:mm:ss
but it returns 1970-01-01 01:00:00 everytime.
Tried with: date('Y-m-d H:i:s', strtotime('2022-09-30T21:39:25.220185674Z'));
or date('Y-m-dTH:i:s', strtotime('2022-09-30T21:39:25.220185674Z'));
Can you help find out which format this is and how i could corretly format such string in PHP?
2
Answers
It’s a ISO 8601 datetime string with microseconds, where
Z
is the timezone "Zulu" orUTC + 0 hours
.ISO 8601 can be parsed with
DateTime()
like this:However This will not work with your string, as the
u
parameter in the format"Y-m-dTH:i:s.uP"
which represents the microseconds, in PHP takes a maximum of6 digits
, and yours has9
.You can resolve this by removing all above 6 digits from the microseconds part of the string with a regex, like
Output:
2022-09-30 21:39:25.220180
The regex explained:
With ‘?’ in the format, all digits after the 6th digit can be cut off.
https://3v4l.org/Upm6v
As of PHP version 8.0.10, strings like ‘2022-09-30T21:39:25.220185674Z’ are recognized by DateTime without any problems.
https://3v4l.org/pI4kO