Is it possible in PHP to get the timezone offset for a given location? E.g. when given the location "Sydney/Australia" to get the timezone offset as "+1100". Bonus would be for this function the keep daylight savings in mind (i.e. it's aware of daylight savings and adjusts the offset according).
Asked
Active
Viewed 1.1k times
8
-
Are you trying to display date/time in a given timezone? – David Snabel-Caunt Oct 11 '10 at 23:02
-
Do you mean official timezone names, or any location in the world? – Pekka Oct 11 '10 at 23:08
-
@david. I'm storing UTC's and I want to be able to convert that time stamp to any local time. – Luke Oct 12 '10 at 00:02
-
@pekka. Offcial time zone names are good enough. – Luke Oct 12 '10 at 00:02
-
@Luke I thought so - then you don't need to calculate the offset and do the arithmetic yourself. See my answer below. – David Snabel-Caunt Oct 12 '10 at 09:59
-
@david. That seems indeed as a slightly nicer way of doing it. Thanks. – Luke Oct 12 '10 at 22:06
-
Thanks guys. Sorry about some confusion. When in the question I asked for '+1100' I didn't mean it that literal. Just an integer 11 would suffice of course. :) – Luke Mar 11 '12 at 09:53
3 Answers
20
You can use the DateTimeZone class.
<?php
$timezone = new DateTimeZone("Australia/Sydney");
$offset = $timezone->getOffset(new DateTime("now")); // Offset in seconds
echo ($offset < 0 ? '-' : '+').round($offset/3600).'00'; // prints "+1100"
?>

Christian Tellnes
- 2,070
- 15
- 17
7
To display a local date/time you can use the following, where 'Europe/Berlin' would be replaced with the user's timezone.
$date = new DateTime($value);
$date->setTimezone(new DateTimeZone('Europe/Berlin'));
echo $date->format('Y-m-d H:i:s');

David Snabel-Caunt
- 57,804
- 13
- 114
- 132
4
Not sure why you need "+1100" (rather than a decimal representation) but you can use this:
$dt = new DateTime(null, new DateTimeZone('Australia/Sydney'));
$offset = $dt->getOffset()/60/60; // 11
$hours = intval($offset);
$minutes = str_pad((string)($offset - $hours) * 60, 2, '0', STR_PAD_RIGHT);
echo $hours.$minutes; // 1100
Replace null
with '2010-10-01'
and you'll get 1000

webbiedave
- 48,414
- 8
- 88
- 101