What are the best practices for handling user input when converting timestamps to dates in PHP to avoid errors like displaying the wrong date?

When converting timestamps to dates in PHP, it is important to handle user input carefully to avoid errors like displaying the wrong date. One best practice is to validate user input to ensure it is in the correct format before converting it to a date. Additionally, using the appropriate timezone settings can help ensure accurate date conversions.

// Validate user input and set timezone before converting timestamp to date
$user_input = "1598918400"; // Example timestamp
$date_format = "Y-m-d H:i:s"; // Desired date format
$timezone = "America/New_York"; // Desired timezone

if (strtotime($user_input) !== false) {
    $date = new DateTime("@$user_input");
    $date->setTimezone(new DateTimeZone($timezone));
    echo $date->format($date_format);
} else {
    echo "Invalid timestamp format";
}