in reply to Re: Finding a remote time
in thread Finding a remote time

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.

Replies are listed 'Best First'.
Re^3: Finding a remote time
by gellyfish (Monsignor) on Jul 17, 2006 at 14:26 UTC

    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\

Re^3: Finding a remote time
by Jenda (Abbot) on Jul 17, 2006 at 15:58 UTC

    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.