如何为Perl的localtime()设置时区?

mik*_*ike 17 perl

在Perl中,我想在特定时区查找本地时间.我一直在使用这种技术:

$ENV{TZ} = 'America/Los_Angeles';
my $now = scalar localtime;
print "It is now $now\n";
# WORKS: prints the current time in LA
Run Code Online (Sandbox Code Playgroud)

但是,这是不可靠的 - 特别是,如果我在设置$ ENV {TZ}之前添加另一个localtime()调用,它会中断:

localtime();
$ENV{TZ} = 'America/Los_Angeles';
my $now = scalar localtime;
print "It is now $now\n";
# FAILS: prints the current time for here instead of LA
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?

eph*_*ent 20

使用POSIX :: tzset.

use POSIX qw(tzset);

my $was = localtime;
print "It was      $was\n";

$ENV{TZ} = 'America/Los_Angeles';

$was = localtime;
print "It is still $was\n";

tzset;

my $now = localtime;
print "It is now   $now\n";
Run Code Online (Sandbox Code Playgroud)
$ perl -v

This is perl, v5.8.8 built for x86_64-linux-thread-multi

Copyright 1987-2006, Larry Wall

Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using "man perl" or "perldoc perl".  If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.

$ perl tzset-test.pl
It was      Wed Apr 15 15:58:10 2009
It is still Wed Apr 15 15:58:10 2009
It is now   Wed Apr 15 12:58:10 2009


Nic*_*son 10

我强烈建议使用模块来执行此操作.具体来说,我建议使用DateTime(参见Perl DateTime WikiCPAN

然后你应该能够做如下的事情:

use strict;
use warnings;
use DateTime;
my $dt = DateTime->now(); # *your* local time assuming your system knows it!


my $clone1 = $dt->clone; # taking a copy.
$clone1->set_time_zone('America/Los_Angeles');


print "$clone1\n";   # output using ISO 8601 format (there a lot of choices)
print "$dt\n";
Run Code Online (Sandbox Code Playgroud)