Current Location: Home> Latest Articles> How to Get and Set Timezone in PHP (With Example Code)

How to Get and Set Timezone in PHP (With Example Code)

M66 2025-10-07

How to Get and Set Timezone in PHP

In PHP development, timezone configuration plays an important role in time calculations, logging, and data processing. If the server’s default timezone differs from your business region, it may cause incorrect time outputs. Therefore, it’s essential to understand how to get and set the PHP timezone properly.

How to Get the Current PHP Timezone

You can use the date_default_timezone_get() function to get the current timezone used by PHP. This function returns a string representing the current timezone name. Example:

// Get current timezone
$current_timezone = date_default_timezone_get();
echo "Current timezone: $current_timezone\n";

How to Set the PHP Timezone

To modify the timezone, use the date_default_timezone_set() function. It takes a string argument that specifies the timezone name. For example, to set the timezone to Eastern Time (US):

// Set timezone to Eastern Time (US)
date_default_timezone_set('America/New_York');
echo "Timezone has been set to Eastern Time\n";

After setting it, you can verify the change by calling date_default_timezone_get() again:

// Get current timezone again
$current_timezone = date_default_timezone_get();
echo "Current timezone: $current_timezone\n";

Notes

  • Timezone names should follow the IANA Time Zone Database format, such as Asia/Shanghai or America/New_York.
  • If the specified timezone is invalid or doesn’t exist, the date_default_timezone_set() function will throw an exception.
  • Changing the timezone does not affect existing timestamps or DateTime objects that were already created.

Conclusion

By using date_default_timezone_get() and date_default_timezone_set(), developers can easily retrieve and modify the default PHP timezone. In real-world applications, it’s best to configure the timezone according to the server’s location or the user’s region to ensure accurate time-related data.