How do I set the timezone for Perl's localtime()?

后端 未结 6 2035

In Perl, I\'d like to look up the localtime in a specific timezone. I had been using this technique:

$ENV{TZ} = \'America/Los_Angeles\';
my $now = scalar loc         


        
6条回答
  •  一整个雨季
    2020-12-05 19:24

    Whilst your code works fine for me on both Linux (Perl 5.10.0) and MacOS X (5.8.9), there is a possible solution.

    The underlying C functons used by Perl (ctime(), localtime(), etc) call tzset() the first time they're invoked, but not necessarily afterwards. By calling it yourself you should ensure that the timezone structures are correctly re-initialised after any change to $TZ.

    Fortunately this is easy - the tzset() function is available in the POSIX module:

    #!/usr/bin/perl -w
    use POSIX qw[tzset];
    
    $ENV{'TZ'} = 'Europe/London';
    tzset();
    print scalar localtime();
    

    NB: some Google searches suggest that this is only necessary with Perl versions up to and including 5.8.8. Later versions always call tzset() automatically before each call to localtime().

提交回复
热议问题