← Back to Chapters

PHP TimeZone Functions

? PHP TimeZone Functions

? Quick Overview

PHP TimeZone functions are used to manipulate and set the time zone for date and time operations. They ensure accurate date-time handling across different geographical regions.

? Key Concepts

  • date_default_timezone_set() – Sets the default timezone for the script.
  • date_default_timezone_get() – Returns the current default timezone.
  • DateTimeZone – Represents a timezone.
  • timezone_offset_get() – Retrieves offset from UTC in seconds.

? Syntax & Theory

PHP uses the server’s default timezone unless explicitly changed. For predictable results, always set a timezone before working with dates.

? View Code Example
// Set and retrieve the default timezone
<?php
date_default_timezone_set("America/New_York");
echo "Current timezone: " . date_default_timezone_get();
echo "<br>";
echo "Current time: " . date("Y-m-d H:i:s");
?>

? Live Output / Explanation

The script sets the timezone to America/New_York and displays the current date and time according to that region.

? View Code Example
// Calculate timezone offset from UTC
<?php
$timezone = new DateTimeZone("America/New_York");
$datetime = new DateTime("now", $timezone);
echo "Time zone offset: " . $timezone->getOffset($datetime) . " seconds";
?>

? Interactive Timezone Diagram

UTC → America/New_York (UTC -5 / -4 DST)

? Use Cases

  • Global applications with users in different countries
  • Scheduling systems and reminders
  • Logging events with consistent timestamps
  • Handling daylight saving time correctly

✅ Tips & Best Practices

  • Always set the timezone at the start of your script.
  • Use DateTime and DateTimeZone for advanced operations.
  • Be aware of daylight saving time changes.
  • Store timestamps in UTC for databases when possible.

? Try It Yourself

  • Set your local timezone and display the current time.
  • Compare offsets between two different timezones.
  • Create two DateTime objects with different timezones and calculate the difference.