What are the best practices for displaying dates and times in PHP to avoid errors?

When displaying dates and times in PHP, it is important to set the correct timezone to avoid errors related to time discrepancies. One of the best practices is to use the DateTime class along with the setTimezone() method to ensure that dates and times are displayed accurately based on the desired timezone.

// Set the default timezone to the desired timezone
date_default_timezone_set('America/New_York');

// Create a new DateTime object with the current date and time
$datetime = new DateTime();

// Set the timezone for the DateTime object
$datetime->setTimezone(new DateTimeZone('Asia/Tokyo'));

// Display the formatted date and time
echo $datetime->format('Y-m-d H:i:s');