How to Set the Timezone in PHP?

Last updated on September 19, 2023

To set the timezone in PHP, we can use the date_default_timezone_set() function. It is used to set the default timezone used by all date and time related operations in the PHP script. It is supported by PHP versions 5.1 and later. We are going to learn how to set different time zones into the web server.

Syntax:

date_default_timezone_set($timezone);

Parameters:

  • The function accepts a single parameter in which the timezone has to pass in the function.

Return value: The function returns a bool value. So it will return false if the $timezone_identifier is not valid.

Before setting the timezone in the web server, we need to get the current timezone of the server so that we know what is the default timezone of the server. To do that we can use PHP built-in function date_default_timezone_get().

echo date_default_timezone_get();
// output: Europe/Berlin

In this example, we are retrieving the current default timezone of the server.

Example 01:

// set the timezone 
date_default_timezone_set("Asia/karachi");
echo date_default_timezone_get();
// output: Asia/Karachi

To set the new timezone on your server of another country we can use the “date_default_timezone_set()” function in PHP. On this link you can find timezones list.

Conclusion:

This article provides an explanation of the PHP built-in function date_default_timezone_set(), along with a practical example demonstrating how to set a specific timezone on a server.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: PHP,