Search code examples
phpdatephp-carbon

How to format datetime from readable to formatable in PHP


I tried to research regarding this issue but didn't see exactly like this since they're asking the reverse format. I'm trying to format readable date to any format but it is returning an error. Please see details below.

String date

23 June, 2021 02:00 PM

Need to convert to

06-23-2021 14:00:00

Code

Carbon::parse('23 June, 2021 02:00 PM');

Error

Could not parse '23 June, 2021 02:00 PM': DateTime::__construct(): Failed to parse time string (23 June, 2021 10:00 AM) at position 14 (1): Double time specification

Solution

  • dont know if its useful for you or not, but in simple php you can do this: (comma can not be present unless you remove it somehow)

    $datestr = "23 June 2021 02:00 PM";
    
    $date = new DateTime($datestr);
    echo $date->format('Y-m-d H:i:s');
    

    and the result would look like: **2021-06-23 14:00:00**