How can input validation and error handling be implemented when retrieving date and time data from HTML forms in PHP to prevent fatal errors related to object conversion?

When retrieving date and time data from HTML forms in PHP, it is important to validate the input to ensure it is in the correct format before attempting any object conversion. This can prevent fatal errors that may occur when trying to convert improperly formatted data into date or time objects. Implementing error handling mechanisms, such as try-catch blocks, can also help capture and handle any conversion errors that may arise.

<?php
// Retrieve date and time data from HTML form
$date = $_POST['date'];
$time = $_POST['time'];

// Validate date format
if (!DateTime::createFromFormat('Y-m-d', $date)) {
    // Handle invalid date format error
    echo "Invalid date format. Please enter date in YYYY-MM-DD format.";
}

// Validate time format
if (!DateTime::createFromFormat('H:i:s', $time)) {
    // Handle invalid time format error
    echo "Invalid time format. Please enter time in HH:MM:SS format.";
}

// Convert date and time strings to DateTime objects
try {
    $dateObj = new DateTime($date);
    $timeObj = new DateTime($time);
} catch (Exception $e) {
    // Handle any conversion errors
    echo "Error converting date or time: " . $e->getMessage();
}
?>