Uncaught PHP Exception Exception: "DateTime::__construct(): Failed to parse time string (2023-09-17 11:32:30.626 AM) at position 24 (A): The timezone could not be found in the database"
I get this error when I try to create a DateTime object in PHP with the datetime string "2023-09-17 11:32:30.626 AM".
It does create a DateTime object with "2023-09-17 11:32:30 AM" and "2023-09-17 11:32:30.626" successfully, though. So it fails when the format is with a microsecond part & AM/PM (without timezone perhaps).
Before I start coding for converting the format, does anyone suggest a simpler solution for this? Like DateTime in C# has a method called ParseExact() and it accepts a specific format other than the default formats.
3
Answers
When you enter time into DateTime it accepts a wide range of human readable timestamps, they are narrowly defined. If you want to include microseconds, you’ll need to use the RFC3339_EXTENDED format, which looks like the following:
You can view the entire list of of supported formats at:
https://www.php.net/manual/en/class.datetimeinterface.php
But since you cannot change the format of the incoming text, then you’ll want to use:
You can use
DateTime::createFromFormat
in this case to define whatever format you are receiving.e.g.
This error comes up is because the format "2023-09-17 11:32:30.626 AM" is not a recognized format for creating a DateTime object in PHP because the milliseconds and AM/PM markers are included.
You can filter the string to remove the milliseconds and then convert it to a 24-hour format. Here’s a suggestion: