Time Zone Function in PHP

Introduction

In this article I explain two important timezone functions, date_default_timezone_get() and date_default_timezone_set() in PHP. Both functions are used for date purposes. I will first discusse the date_default_timezone_get() function and then the date_default_timezone_set() function.

Syntax

The date_default_timezone_get() function gets the default timezone. You can set the timezone in your project used for this but this function only reads the timezone environment variable in PHP 5.4. Such as:

date_default_timezone_get(void);

This function returns string output.

Example

Getting the default timezone.

 

<?php

//get timezone

date_default_timezone_set('Europe/London');

//match your timezone

if (date_default_timezone_get())

{

    echo 'date_default_timezone_set: ' . date_default_timezone_get() . "<br>";

}

//match your time with date

if (ini_get('date.timezone'))

{

    echo 'date.timezone: ' . ini_get('date.timezone');

}

?>

Output

timeget.jpg 

Example 

 

Getting the abbreviation of a timezone.

 

<?php

//get timezone function

date_default_timezone_set('Europe/London');

//display in array formate

echo date_default_timezone_get() . ' => ' . date('e') . ' => ' . date('T');

?>

Output

timeget2.jpg

Next, I will discuss the date_default_timezone_set() function in PHP.

Syntax

The date_default_timezone_set() function sets the default timezone. Instead of using this function you can set the default timezone in the "php.ini" settings.

date_default_timezone_set($timezone_identifier);

 

Parameter Description
timezone_identifier The list of valid identifiers is available in the List of Supported Timezones.

This function returns false when the timezone_identifier is not valid otherwise it returns true.

Example

<?php

//set timezone

date_default_timezone_set('America/Los_Angeles');

$t_zone = date_default_timezone_get();

//compare your timezone with ini-set timezone

if (strcmp($t_zone, ini_get('date.timezone')))

{

    echo 'Script timezone differs from ini-set timezone.';

}

else

{

    echo 'Script timezone and ini-set timezone match.';

}

?>

Output

timeset.jpg


Similar Articles