How to Handle Timezones in PHP

In our world, we have different timezones. Each timezone follows a uniform standard time for the countries and their subdivision which falls under a timezone.

As a developer, sometimes you need to deal with different timezones. You may need to execute a code on the basis of the date and time of specific timezones. PHP provides a few classes and functions that help to handle timezones in the application. Let’s see how to handle timezones in PHP.

Get Default Timezone of Server

PHP websites run on a server. Each server has its default timezone. If you want to know the timezone of your server, use the code below.

<?php
if (date_default_timezone_get()) {
    echo 'Timezone is: ' . date_default_timezone_get();
}

One can also check the server’s timezone in the php.ini file. Open the file and search for date.timezone and you will get the timezone. In my case, I can see the timezone set to Asia/Kolkata.

date.timezone=Asia/Kolkata

When you print the date and time, you will get it as per the timezone of your server. For me, it will be local time in India.

<?php
echo date('Y-m-d H:i'); // output will be current date and time in India

Change Default Timezone of Your Server

If someone wants to change the default timezone of the server, use the method date_default_timezone_set() and pass the timezone string to this function. You can get a list of available timezones here.

For instance, I set ‘Pacific/Nauru’ as the default timezone.

<?php
date_default_timezone_set('Pacific/Nauru');

Alternatively, you can also set the timezone into the php.ini file. Open it, search for date.timezone and assign value to it as follows.

date.timezone=Pacific/Nauru

When you change the php.ini settings, you need to restart the apache server to reflect the new changes.

Now if you print the date and time again, you will get it as per the ‘Pacific/Nauru’ timezone.

How to Handle Timezones in PHP On The Fly

There might be some scenarios where you want to get dates and times from different time zones on the fly. You can’t set or use the default timezone in such cases. To deal with those scenarios, use the DateTime class provided in PHP.

Let’s say you want to get the current date and time of the timezone ‘America/Los_Angeles’. For this, you can use the below code.

<?php
$datetime = new DateTime;
$otherTZ  = new DateTimeZone('America/Los_Angeles');
$datetime->setTimezone($otherTZ);
echo $datetime->format('Y-m-d H:i:s');

The above code sets the timezone ‘America/Los_Angeles’ at runtime and gives you the date and time accordingly.

This is how one can handle timezones in PHP. I hope you understand the topic. I would like to hear your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *