PHP date_default_timezone_get() Function

What is PHP date_default_timezone_get() Function?

To get the default timezone used by a script, use PHP date_default_timezone_get() function. To know what timezone all the date/time functions are using, use this function.

To retrieve the default timezone, the date_default_timezone_get() function uses the following steps serially-

  • At first, it check whether any timezone is set by the date_default_timezone_set() function in the script.
  • If nothing found, then, it look at the date.timezone option in the php.ini file.
  • If nothing found, the function returns the UTC as the default timezone.

Syntax:

date_default_timezone_get()

Parameters:

This function doesn’t accept any parameter.

Return Values:

The function returns the timezone identifier.

Examples:

Example 1: When no timeone is set in the script-

<?php
echo "Current timezone is: " . date_default_timezone_get();
?>

Output:

Current timezone is: America/New_York

Explanation:

As there is no default timezone is set in the script by date_default_timezone_set() function, the function looks for the timezone at date.timezone option in the php.ini file and get the time that you see in the output.

Example 2: When timezone is already set in the script-

<?php
date_default_timezone_set("America/New_York");
echo "Current timezone is: " . date_default_timezone_get();
?>

Output:

Current timezone is: America/New_York

Explanation:

The default timezone “America/New_York” is set by the function at line 2. so, the function in the next line displays the timezone.

Example 3: When no timezone is set in the script and in php.ini file-

<?php
echo "Default timezone set at date.timezone in php.ini is: " . ini_get('date.timezone');
echo "<br />";
echo "Current timezone is: " . date_default_timezone_get();
?>

Output:

Default timezone set at date.timezone in php.ini is:
Current timezone is: UTC

Explanation:

The ini_get() function in line 2 displays that there is no timezone set in the php.ini file. And, there is no default timezone set at the script level using date_default_timezone_set() function. Hence, in the line 4, the function displays UTC as the default timezone.

Practical usages of PHP date_default_timezone_get() function:

By using this function, you get to know that you’re using the correct timezone. And, you can undoubtedly perform the date and time related operations in your web application.

PHP Version Support:

PHP 5 >= 5.1.0, PHP 7, PHP 8

Summary: PHP date_default_timezone_get() Function

The date_default_timezone_get() function is a useful PHP built-in date/time function. Your application may need to run in different geographical location. The function checks whether your web application is running in the correct timezone.

Reference:

https://www.php.net/manual/en/function.date-default-timezone-get.php