skip to Main Content

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


  1. 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:

    new DateTime("2023-09-17T11:32:30.626+00:00")
    

    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:

    $dateTime = DateTime::createFromFormat('Y-m-d h:i:s.u a', $dateString);
    
    Login or Signup to reply.
  2. You can use DateTime::createFromFormat in this case to define whatever format you are receiving.

    DateTime::createFromFormat('Y-m-d H:i:s.v A', '2023-09-17 11:32:30.626 AM')
    

    e.g.

    $string = '2023-09-17 11:32:30.626 AM';
    $format = 'Y-m-d H:i:s.v A';
    $dt     = DateTime::createFromFormat($format, $string);
    echo $dt->format(DATE_RFC3339_EXTENDED);
    
    2023-09-17T11:32:30.626-04:00
    
    Login or Signup to reply.
  3. 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:

    $dateString = "2023-09-17 11:32:30.626 AM";
    
    // Remove the milliseconds and AM/PM
    $dateString = preg_replace('/.d+s(AM|PM)/', ' $1', $dateString);
    
    // Create a DateTime object
    $dateTime = DateTime::createFromFormat('Y-m-d h:i:s A', $dateString);
    
    if ($dateTime === false) {
        echo "Failed to parse the date string.";
    } else {
        echo $dateTime->format('Y-m-d H:i:s'); // Output in 24-hour format
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search