in reply to Finding a remote time

You can set $ENV{TZ} and then use the tzset from POSIX:

use POSIX qw(tzset); use strict; + print scalar localtime(); + $ENV{TZ} = 'EST'; + tzset(); + print scalar localtime();

/J\

Replies are listed 'Best First'.
Re^2: Finding a remote time
by Fletch (Bishop) on Jul 17, 2006 at 13:14 UTC

    Actually you might want to use:

    use POSIX qw( tzset ) sub localtime_in { local $ENV{TZ} = shift; tzset; localtime } $localtime_in_EST = localtime_in( "EST" );

    Otherwise you've globally change the timezone for any other calls to (gm|local)time elsewhere in your code.

    And personally I've used both some variant of twiddling $ENV{TZ} like this and DateTime.

      Localising the $ENV{TZ} isn't sufficient to prevent the effect being global, tzset() will need to be called after the value has been reverted to restore the timezone used by localtime(). For example:

      use POSIX qw(tzset); use strict; + print scalar localtime(); + sub localtime_in { local $ENV{TZ} = 'EST'; + tzset(); + localtime(); } + print scalar localtime_in(); print scalar localtime();

      Off the top of my head a way of fixing that would be something like:

      use POSIX qw(tzset); use strict; + print scalar localtime(); + sub localtime_in { my $rc; my @rc; { local $ENV{TZ} = shift; tzset(); wantarray ? @rc = localtime() : $rc = localtime(); } tzset(); return wantarray ? @rc : $rc; } + print scalar localtime_in('EST'); print scalar localtime();

      /J\

      Doesn't seem to work for me using ActivePerl v5.8.7 build 813 under Windows Server 2003. I do get the local time no matter whether I set $ENV{TZ} to EST or CET (my timezone). Tried even localtime_in( "0500" );

      Update: The DateTime solution works though. So if you need to make portable code, use DateTime;

        You've got your explanation right in your post. Wintendo POSIX support is notoriously flakey to non-existent. I'd bet the DateTime solutions would still work.