What are some best practices for handling time calculations in PHP to avoid issues with daylight saving time changes?
When handling time calculations in PHP, it is important to use timezone-aware functions and avoid relying solely on functions like `strtotime` or `date`. To avoid issues with daylight saving time changes, always store and manipulate timestamps in UTC and only convert to local time for display purposes.
// Set default timezone to UTC
date_default_timezone_set('UTC');
// Get current timestamp in UTC
$currentTimeUTC = time();
// Convert UTC timestamp to local time for display
$localTimezone = new DateTimeZone('America/New_York');
$localTime = new DateTime('@' . $currentTimeUTC);
$localTime->setTimezone($localTimezone);
echo $localTime->format('Y-m-d H:i:s');
Related Questions
- How important is hands-on experience and project-based learning in mastering PHP, JavaScript, Zendframework, and MySQL compared to traditional classroom instruction?
- What is the potential impact of using target=_blank in links on session management in PHP?
- How can the code be refactored to adhere more closely to object-oriented programming principles in PHP?