1

Basically my website is worldwide and I need to be able to detect users' time zones and display accurate times. I have this really neat script which used to work flawlessly well until now. It needs a timezone offset which I fetch with javascript and pass through a cookie.

if(!empty($_COOKIE['tz']) && $_COOKIE['tz']>=-12 && $_COOKIE['tz']<=13){
    $offset = $_COOKIE['tz'];
    $tz = timezone_name_from_abbr(null, $offset * 3600, true);
    if($tz === false) $tz = timezone_name_from_abbr(null, $offset * 3600, false);
    date_default_timezone_set($tz);
}else{
    date_default_timezone_set('UTC');
}

The problem is that currently the timezone I'm testing in is Europe/Helsinki, which is UTC+2 (without daylight savings), but for some reason timezone_name_from_abbr() decides 2*3600 is Europe/Paris. I'm really bad with dates and time zones, I desperately need help, please!

php_nub_qq
  • 15,199
  • 21
  • 74
  • 144

1 Answers1

5

In general, the idea of locating an exact time zone (such as Europe/Helsinki or Europe/Paris) based solely on an offset (such as UTC+02:00) is not possible with any sort of reliability or accuracy. Many time zones share the same offset at any given point in time, and many time zones switch between two different offsets throughout the year due to daylight saving time rules.

You can see a list of all of the time zones, and their standard and daylight offsets here.

Even the idea of going from a time zone abbreviation to a time zone is not sound, as several time zones could share the same abbreviation. For example, "CST" could be "Central Standard Time" (USA), "Central Standard Time" (Australia), "Central Summer Time" (Australia), "China Standard Time", or "Cuba Standard Time". See this list for details.

Given these concerns, it is rather strange that PHP would give you a function called timezone_name_from_abbr. I recommend avoiding using it, as it is clearly conceptually flawed.

If you're after detection of the user's time zone, consider using the JavaScript library jsTimeZoneDetect. It is not perfect either, but it works in general, and is based on a more logical algorithm.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575