Alex Rivera | Logout

What's the best way to get the UTC offset in Perl?

Asked 2010-01-26T23:35:08.783
13

I need to get the UTC offset of the current time zone in Perl in a cross platform (Windows and various flavors of Unix) way. It should meet this format:

zzzzzz, which represents ±hh:mm in relation to UTC

It looks like I should be able to get it via strftime(), but it doesn't appear to be consistent.

Unix:

Input: perl -MPOSIX -e "print strftime(\"%z\", localtime());"
Output: -0700

Windows:

Input: perl -MPOSIX -e "print strftime(\"%z\", localtime());"
Output: Mountain Standard Time

While it appears that Unix is giving me what I want (or at least something close), Windows is not. I'm pretty sure I can do it with Date::Time or similar, but I'd really like to not have any dependencies that I can't guarantee a user will have due to our wide install base.

Am I missing something obvious here? Thanks in advance.

Edit
Report

1 Answer

0

You can compute the difference between localtime($t) and gmtime($t). Here is my version inspired by mob's answer:

use strict;
use warnings;    

sub tz_offset
{
    my $t = shift;
    my @l = localtime($t);
    my @g = gmtime($t);

    my $minutes = ($l[2] - $g[2] + ((($l[5]<<9)|$l[7]) <=> (($g[5]<<9)|$g[7])) * 24) * 60 + $l[1] - $g[1];
    return $minutes unless wantarray;
    return (int($minutes / 60), $minutes % 60);
}

push @ARGV, time;
foreach my $t (@ARGV) {
    printf "%s (%d): %+03d%02u\n", scalar localtime($t), $t, tz_offset($t);
}
answered 2011-06-21T16:26:20.277

Your Answer