[sf-perl] Getting the timezone

David Alban extasia at extasia.org
Fri Nov 17 18:40:32 PST 2006


Greetings,

Assume I want to derive a string representing the local host's
timezone.  The string is of the form sNNNN where s is a plus or minus
sign, and the N's are digits.  E.g.:

  -0800
  +0000
  +0100

Assume I want to do this in "pure perl".  That is, I don't want to use
any modules that aren't in the core perl distibution.  Assume you're
not allowed to ask why.

Can anyone see any reason not to do the following?

Thanks,
David

  use Time::Local;

  use constant SECONDS => 1;
  use constant MINUTES => 60 * SECONDS;
  use constant HOURS   => 60 * MINUTES;

  use constant SECONDS_FIELD => 1;
  use constant MINUTES_FIELD => 1;
  use constant HOURS_FIELD   => 2;
  use constant DAY_FIELD     => 3;
  use constant MONTH_FIELD   => 4;
  use constant YEAR_FIELD    => 5;

  sub time_zone {
    my $time = time;

    my ( $local_year,
         $local_month,
         $local_day,
         $local_hours,
         $local_minutes,
         $local_seconds,
       ) = ( localtime $time )[ YEAR_FIELD,
                                MONTH_FIELD,
                                DAY_FIELD,
                                HOURS_FIELD,
                                MINUTES_FIELD,
                                SECONDS_FIELD,
                              ];

    my ( $gm_year,
         $gm_month,
         $gm_day,
         $gm_hours,
         $gm_minutes,
         $gm_seconds,
       ) = ( gmtime $time )[ YEAR_FIELD,
                             MONTH_FIELD,
                             DAY_FIELD,
                             HOURS_FIELD,
                             MINUTES_FIELD,
                             SECONDS_FIELD,
                           ];

    my $seconds_local = timelocal( $local_seconds,
                                   $local_minutes,
                                   $local_hours,
                                   $local_day,
                                   $local_month,
                                   $local_year,
                                 );

    my $seconds_gm    = timelocal( $gm_seconds,
                                   $gm_minutes,
                                   $gm_hours,
                                   $gm_day,
                                   $gm_month,
                                   $gm_year,
                                 );

    my $difference = $seconds_local - $seconds_gm;

    $difference > 24 * HOURS and return sprintf "+????";

    my $sign = $difference < 0 ? "-" : "+";

    $difference = abs $difference;

    my $hours_offset   = int ( $difference / HOURS );
    my $minutes_offset = int ( $difference % HOURS );

    sprintf "%s%02d%02d", $sign, $hours_offset, $minutes_offset;
  } # time_zone


-- 
Live in a world of your own, but always welcome visitors.


More information about the SanFrancisco-pm mailing list