Home > front end >  PHP: How to convert textual date string to a valid date
PHP: How to convert textual date string to a valid date

Time:12-03

I have a date string in this format:

Thu, Oct 13, 2022

Is there a short way to confirm it into date with format: 2022-10-13

Thanks for any ideas

CodePudding user response:

Yes, you can use the PHP DateTime class to convert a textual date string to a valid date. Here is an example:

$dateString = 'Thu, Oct 13, 2022';
$date = DateTime::createFromFormat('D, M d, Y', $dateString);
$formattedDate = $date->format('Y-m-d');

// Output: 2022-10-13
echo $formattedDate;

The DateTime::createFromFormat() method accepts the date string and the format of the date string as arguments, and returns a DateTime object that represents the date. Then, the DateTime::format() method can be used to convert the date to the desired format.

  • Related