How to Set the Timezone in PHP

Sheeraz Gul Feb 02, 2024
How to Set the Timezone in PHP

The timezone in PHP can be changed using the php.ini settings. PHP also provides a built-in function date_default_timezone_set() which can also set the timezone in PHP.

This tutorial demonstrates how to set the timezone in PHP.

Set the Timezone in PHP

There are two methods to set the timezone in PHP. One is from the php.ini file and the other from the built-in method.

Use the PHP.INI File to Set the Timezone in PHP

Follow the steps below to set the timezone using the php.ini file:

  • First of all, create the phpinfo() file to show the time.

    PHP Info Timezone

  • Go to your PHP directory and open the php.ini file.
  • Search for the date.timezone.

    PHP Date Timezone

  • Remove the comment and set the timezone to any value, for example, Asia/Kolkata.

    PHP Set Timezone

  • Once the timezone is set, restart the Apache server.
  • Once the server is restarted, the timezone will be changed.

Use the date_default_timezone_set() Method to Set the Timezone in PHP

The date_default_timezone_set() is a built-in method in PHP which is used to set the timezone in PHP. The method returns false if the timezone is valid; otherwise, it will always return true.

This method is supported in PHP 5.1+ versions. The syntax for this method is:

date_default_timezone_set(timezone)

Where timezone is the timezone like UTC, GMT, or Asia/Kolkata, the list of timezones can be found here.

Let’s try an example for the date_default_timezone_set() method:

<?php
echo "The Default Timezone: ";
echo date_default_timezone_get();
echo "<br><br>";
date_default_timezone_set("Europe/Rome");
echo "The Updated Timezone: ";
echo date_default_timezone_get();
?>

The code above shows the default timezone and then updates it using the date_default_timezone_set() method. See output:

The Default Timezone: UTC

The Updated Timezone: Europe/Rome
Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - PHP Timezone