PHP date format from a very strange saved datetime string

77 views Asked by At

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?

2

There are 2 answers

3
GrumpyCrouton On BEST ANSWER

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
0
imvain2 On

You can use PHP's strtotime to convert it to a timestamp. Then use the Date function and pass it variables to output the proper format.

date("F j, Y, g:i a",strtotime("20230829130000"))