-1

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?

Omer
  • 1,727
  • 5
  • 28
  • 47

2 Answers2

1

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
GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71
  • This is correct but the comment in my question is doing the same thing but with less code. – Omer Aug 21 '23 at 19:17
  • @Omer It's not the same thing, but it is similar. Using `strtotime()` is a more limited solution because you cannot specify what the date format is, and it can have a hard time with some date formats. Using DateTime is also more readable and it is more understandable what it is doing. Both work though in your case. – GrumpyCrouton Aug 21 '23 at 19:43
  • 1
    @Omer Also, my solution can be written in 1 line as well, e.g `DateTime::createFromFormat('YmdHis', '20230829130000')->format('F j, Y, g:i a')` – GrumpyCrouton Aug 21 '23 at 19:45
1

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"))

imvain2
  • 15,480
  • 1
  • 16
  • 21