How to parse a date string into a DateTime object in PHP?

In PHP, you can use the DateTime class along with the createFromFormat() method to parse a date string into a DateTime object.

Here's an example of how to do it:

$dateString = "2022-12-31"; $dateObj = DateTime::createFromFormat('Y-m-d', $dateString); if ($dateObj) { $formattedDate = $dateObj->format('Y-m-d'); echo "Parsed date: " . $formattedDate; } else { echo "Invalid date string"; }

In this example, the $dateString variable represents the date string that you want to parse. The createFromFormat() method takes two parameters: the format of the input date string and the date string itself. In this case, 'Y-m-d' represents the format of the date string, which matches the format YYYY-MM-DD of the provided example date.

If the date string is parsed successfully, the method will return a DateTime object, which can then be formatted using the format() method. In the example, it's formatted as 'Y-m-d', but you can choose any supported format you need.

If the date string is not in the expected format or is invalid, the createFromFormat() method will return false. You can use an if statement to check for this case and handle it accordingly.