What are the best practices for handling timestamp calculations and formatting in PHP to avoid confusion with time zones and daylight saving time changes?

When handling timestamp calculations and formatting in PHP to avoid confusion with time zones and daylight saving time changes, it's best to always work with timestamps in UTC format. This ensures consistency across different time zones and eliminates the need to worry about daylight saving time changes. When displaying timestamps to users, convert them to the appropriate time zone for their location.

// Set default timezone to UTC
date_default_timezone_set('UTC');

// Get current timestamp in UTC
$timestamp = time();

// Convert timestamp to user's local time zone
$user_timezone = new DateTimeZone('America/New_York');
$user_time = new DateTime();
$user_time->setTimestamp($timestamp);
$user_time->setTimezone($user_timezone);

// Format timestamp for display
$formatted_time = $user_time->format('Y-m-d H:i:s');

echo $formatted_time;