Search code examples
phpdatedatetimedate-format

PHP date format from a very strange saved datetime string


I have a date time string saved in DB as 20230829130000 and in actuality this string means: 2023-08-29 13:00:00

I want it to be formatted properly like this: August 22, 2023, 1:00 pm

Is there any PHP function to format the date from this string or do I need to break the string and then format it?


Solution

  • You can use the DateTime object for this.

    $inputString = '20230829130000';
    $dateTime = DateTime::createFromFormat('YmdHis', $inputString);
    $formattedDate = $dateTime->format('F j, Y, g:i a');
    
    echo $formattedDate; // Output: August 29, 2023, 1:00 pm