What are the best practices for converting a user-input date with possible time to midnight (00:00) in PHP?

When converting a user-input date with possible time to midnight (00:00) in PHP, it is important to ensure the date is in a valid format before manipulating it. One approach is to use the DateTime class to parse the input date, set the time to midnight using the setTime() method, and then format the date back to the desired format.

$userInput = "2022-12-31 15:30:00"; // Example user-input date with time
$dateTime = DateTime::createFromFormat('Y-m-d H:i:s', $userInput);
$dateTime->setTime(0, 0, 0);
$midnightDate = $dateTime->format('Y-m-d H:i:s');

echo $midnightDate; // Output: 2022-12-31 00:00:00