27

How would I go about converting a timezone name ("Asia/Dubai", "Europe/Andorra", etc) to a GMT offset in hours (or even seconds, since I can convert it from there).

Most people ask for the reverse, but I need to get a timezone offset from the timezone name provided by GeoNames.

Andrew M
  • 4,208
  • 11
  • 42
  • 67
  • This doesn't directly answer your question, but may solve your problem. Looks like you can query GeoNames directly for the offset, like this: http://api.geonames.org/timezoneJSON?lat=47.01&lng=10.2 – Ben Lee Jan 18 '11 at 19:56
  • Yeah, I am actually using GeoNames as a primary. The main problem is that they are currently overloaded, so I am trying to have a backup for when they are. – Andrew M Jan 18 '11 at 19:59
  • Possible duplicate of [UTC Offset in PHP](https://stackoverflow.com/questions/193499/utc-offset-in-php) – HMagdy Oct 11 '18 at 18:16

3 Answers3

51

you can use the following

<?php

$timezone = 'Pacific/Nauru';
$time = new \DateTime('now', new DateTimeZone($timezone));
$timezoneOffset = $time->format('P');
?>
cloakedninjas
  • 4,007
  • 2
  • 31
  • 45
Cecil Zorg
  • 1,478
  • 13
  • 15
26

Another option would be to use the available DateTimeZone::getOffset() method, which returns the offset in seconds for the time zone at the specified date/time.

$timezone = new DateTimeZone("Europe/Andorra");
$offset   = $timezone->getOffset(new DateTime);
salathe
  • 51,324
  • 12
  • 104
  • 132
  • 2
    I prefer this answer because it gives me the seconds. As opposed to `format('P')` which returns `hh:mm` format. – hpaknia Nov 21 '18 at 06:39
15

I like using PHP Carbon:

$offset = Carbon::now('Europe/Andorra')->offsetHours;
mopo922
  • 6,293
  • 3
  • 28
  • 31