Software Developer

Get Abbreviated Timezone From Offset Minutes in PHP

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:

JavaScript

(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.

PHP

/**
 * 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;
    $location = timezone_name_from_abbr('', $seconds, 1);
    $date = new DateTime(null, new DateTimeZone($location));
    return $date->format('T');
}

By

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]