如何为 Perl 的 localtime() 设置时区? [英] How do I set the timezone for Perl's localtime()?

查看:43
本文介绍了如何为 Perl 的 localtime() 设置时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

$ENV{TZ} = 'America/Los_Angeles';我的 $now = 标量本地时间;print "现在是 $now
";# WORKS:打印洛杉矶的当前时间

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

localtime();$ENV{TZ} = '美国/洛杉矶';我的 $now = 标量本地时间;print "现在是 $now
";# FAILS:打印这里的当前时间而不是 LA

有没有更好的方法来做到这一点?

解决方案

使用 POSIX::tzset.

使用POSIX qw(tzset);我的 $was = 本地时间;print "它是 $was
";$ENV{TZ} = '美国/洛杉矶';$was = 本地时间;print "它仍然是 $was
";tzset;我的 $now = 本地时间;print "现在是 $now
";

<前>$ perl -v这是 perl,为 x86_64-linux-thread-multi 构建的 v5.8.8版权所有 1987-2006,拉里·沃尔Perl 只能根据艺术许可或GNU 通用公共许可证,可在 Perl 5 源工具包中找到.Perl 的完整文档,包括常见问题列表,应该在这个系统使用man perl"或perldoc perl".如果您可以访问Internet,将您的浏览器指向 http://www.perl.org/,Perl 主页.$ perl tzset-test.pl这是 2009 年 4 月 15 日星期三 15:58:10现在仍然是 2009 年 4 月 15 日星期三 15:58:10现在是 2009 年 4 月 15 日星期三 12:58:10

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 localtime;
print "It is now $now
";
# WORKS: prints the current time in LA

However, this is not reliable -- notably, if I prepend another localtime() call before setting $ENV{TZ}, it breaks:

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

Is there a better way to do this?

解决方案

Use POSIX::tzset.

use POSIX qw(tzset);

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

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

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

tzset;

my $now = localtime;
print "It is now   $now
";

$ 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

这篇关于如何为 Perl 的 localtime() 设置时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆