This PHP function gets the abbreviated timezone based on the offset. The offset is the difference in time between the current locale and UTC.
This is useful if you have the timezone offset from JavaScript which is given in minutes, and you need to get the pretty abbreviated timezone for display. The abbreviated timezones are, for example: EST, PST, or during Daylight Savings Time: EDT, PDT.
Although the function takes minutes, you can easily convert it to take seconds or hours if you need to. I used minutes because I’m getting the offset from this JavaScript which gives the offset in minutes:
(new Date()).getTimezoneOffset();
That also gives the offset sign backwards, that is, it gives eastern offsets as negative and western offsets as positive, which is backwards from how I usually deal with offsets in PHP.
The following function takes the minutes, as is, from JavaScript, so it expects eastern offsets as negative and western offsets as positive. Consider that if you alter the function to work with offset hours from PHP or something, which use negative for western and positive for eastern.
/** * Get abbreviated timezone from offset minutes * * @param int $min Offset in minutes, as is from JavaScript e.g. eastern offsets as negative and western offsets as positive * * @return string Like EST, PST, EDT, PDT */ function timezone_abbrev_from_min($min){ $min = 0 - $min;// flip the sign because JavaScript gets the offset backwards $seconds = $min * 60; // PHP bug https://bugs.php.net/bug.php?id=73988 and https://bugs.php.net/bug.php?id=44780 if(660 == $min) $location = 'Asia/Magadan'; // NOTE: change 1 to 0 to use no DST else $location = timezone_name_from_abbr('', $seconds, 1); try { $z = new DateTimeZone($location); } catch(Exception $e) { // error_log(sprintf('ERROR (incoming min = %s, seconds = %s, $location = %s): %s<br>', $min, $seconds, $location, $e->getMessage())); $z = new DateTimeZone('America/New_York'); } $date = new DateTime(null, $z); return $date->format('T'); }
Questions and Comments are Welcome