Adjusting Time Zone in PHP with Datetime/Datetimezone

Adjusting time zone in PHP with DateTime / DateTimeZone

Here are a couple of functions using the DateTime classes. The first one will return the difference in seconds between two timezones. The second returns a "translation" of the time from one timezone to another.

function timezone_diff($tz_from, $tz_to, $time_str = 'now')
{
$dt = new DateTime($time_str, new DateTimeZone($tz_from));
$offset_from = $dt->getOffset();
$timestamp = $dt->getTimestamp();
$offset_to = $dt->setTimezone(new DateTimezone($tz_to))->setTimestamp($timestamp)->getOffset();
return $offset_to - $offset_from;
}

function time_translate($tz_from, $tz_to, $time_str = 'now', $format = 'Y-m-d H:i:s')
{
$dt = new DateTime($time_str, new DateTimezone($tz_from));
$timestamp = $dt->getTimestamp();
return $dt->setTimezone(new DateTimezone($tz_to))->setTimestamp($timestamp)->format($format);
}

Demo:

$los_angeles_time = '2009-09-18 05:00:00';
$los_angeles_tz = 'America/Los_Angeles';
$hawaii_tz = 'Pacific/Honolulu';

$los_angeles_hawaii_diff = timezone_diff($los_angeles_tz, $hawaii_tz, $los_angeles_time);
echo $los_angeles_hawaii_diff . '<br />';

$hawaii_time = time_translate($los_angeles_tz, $hawaii_tz, $los_angeles_time);
echo $hawaii_time . '<br />';

How to convert between time zones in PHP using the DateTime class?

What you're looking for is this:

$triggerOn = '04/01/2013 03:08 PM';
$user_tz = 'America/Los_Angeles';

echo $triggerOn; // echoes 04/01/2013 03:08 PM

$schedule_date = new DateTime($triggerOn, new DateTimeZone($user_tz) );
$schedule_date->setTimeZone(new DateTimeZone('UTC'));
$triggerOn = $schedule_date->format('Y-m-d H:i:s');

echo $triggerOn; // echoes 2013-04-01 22:08:00

Converting Time with timezone PHP

You can try this code, this will work for you and you can set the timezone as per your need.

// Input  : '2021-01-20T19:03:52.355+0300';
// Output : '20-01-2021 23.03.52,355000 +07:00';

date_default_timezone_set('Europe/London');
$datetime = new DateTime('2021-01-20T19:03:52.355+0300');

// timezone to convert.
$la_time = new DateTimeZone('Asia/Krasnoyarsk');
$datetime->setTimezone($la_time);
echo $datetime->format('d-m-Y H.i.s,u P');

Output:

20-01-2021 23.03.52,355000 +07:00

Changing timezone of a retrieved date in php

Your input datetime is in UTC, not user's timezone. So first you must create datetime object in UTC, and then set/change timezone to user's :

$dt = new DateTime('2013-09-15 08:45:00', new DateTimeZone('UTC'));
print_r($dt);
/*
DateTime Object
(
[date] => 2013-09-15 08:45:00
[timezone_type] => 3
[timezone] => UTC
)
*/

Now you have datetime in UTC timezone. If you wish to change timezone, just call ->setTimezone() on DateTime object :

$dt->setTimezone(new DateTimeZone('Europe/Berlin'));
print_r($dt);
/*
DateTime Object
(
[date] => 2013-09-15 10:45:00
[timezone_type] => 3
[timezone] => Europe/Berlin
)
*/

p.s. because input 2013-09-15 08:45:00 is in standard datetime format, you don't need to use DateTime::createFromFormat.

Timezone conversion in php

You can use the datetime object or their function aliases for this:

Example (abridged from PHP Manual)

date_default_timezone_set('Europe/London');

$datetime = new DateTime('2008-08-03 12:35:23');
echo $datetime->format('Y-m-d H:i:s') . "\n";
$la_time = new DateTimeZone('America/Los_Angeles');
$datetime->setTimezone($la_time);
echo $datetime->format('Y-m-d H:i:s');

Edit regarding comments

but i cannt use this method because i need to show date in different time zones as the user login from different locations

That's not a problem. When a user logs in, you determine his timezone and set it to your DateTime object just like shown. I'm using a similar approach in one of my projects and it works like a charm.

in the database i need to get the dates in any single timezone, then only it can be processed properly

You store the time either as a timestamp or a datetime in one timezone. When you query a DateTime field, you either convert the time in a DateTime object to this timezone or - if your db supports it - query with the selected timezone.

How to set time zone with DateTime object?

look at DateTimeZone

$date = new DateTime('now',new DateTimeZone("Europe/Rome"));

PHP date() with timezone?

For such task, you should really be using PHP's DateTime class. Please ignore all of the answers advising you to use date() or date_set_time_zone, it's simply bad and outdated.

I'll use pseudocode to demonstrate, so try to adjust the code to suit your needs.

Assuming that variable $tz contains string name of a valid time zone and variable $timestamp contains the timestamp you wish to format according to time zone, the code would look like this:

$tz = 'Europe/London';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
echo $dt->format('d.m.Y, H:i:s');

DateTime class is powerful, and to grasp all of its capabilities - you should devote some of your time reading about it at php.net. To answer your question fully - yes, you can adjust the time zone parameter dynamically (on each iteration while reading from db, you can create a new DateTimeZone() object).

Changing the time zone in PHP is not working

getTimestamp returns a UNIX Epoch timestamp. UNIX timestamps are always the same all over the world. Time zones only affect human readable time, e.g. when you do $now->format('H:i:s').

Also see https://stackoverflow.com/a/4812178/476 for more explanation.

Setting time zone in php

Function date_default_timezone_set()>= 5.1.0 set timezone globally.

If you need to set timezone locally, for specific variable, you can use DateTime>= 5.2.0 and DateTimezone>= 5.2.0 classes, like:

$dt = new DateTime('now', new DateTimezone('Asia/Dhaka'));
echo $dt->format('F j, Y, g:i a');

Here is the list of all available timezones in PHP.


Since non of the above functions will work on PHP version 4.x, you have no other way to set timezone, rather that setting your server time to your timezone, or add offset to time() functions, like:

echo date('F j, Y, g:i a', time() - 6*3600); # Bangladesh is in UTC+6


Related Topics



Leave a reply



Submit