Perl环境下常见的时区的处理
2013-11-10 16:23:18 阿炯

本站赞助商链接,请多关照。 收集了一些时间处理模块,重点介绍时区在这其中的操作。
perl -MPOSIX print strftime('%z', localtime()),"\n";

POSIX中有
my $t = time();
my $utc = mktime(gmtime($t));
my $local = mktime(localtime($t));

%z is Linux specific
From manpage:

%Z Time zone name or abbreviation, or no bytes if no time zone information exists.

Also, "%z" seems to be Linux specific - does not work on Solaris either:

$ perl -MPOSIX -e 'print strftime("%z", localtime()),"\n"'
+0800
$ perl -MPOSIX -e 'print strftime("%Z", localtime()),"\n"'
CST

perl -MPOSIX -e 'print strftime "%Z (%z)\n",localtime'
CST (+0800)

perl -MPOSIX -le 'tzset; print for tzname'
CST
CDT

use POSIX;
$tz = strftime("%Z", localtime());
或者可以通过localtime()与gmtime()它们之间的差值进行计算。


使用DateTime::Format::Strptime来处理时间

my $val = "20090103 12:00";

my $format = new DateTime::Format::Strptime(pattern => '%Y%m%d %H:%M',time_zone => 'GMT');

my $date = $format->parse_datetime($val);

print $date->strftime("%Y%m%d %H:%M %Z")."\n";

$date->set_time_zone("America/New_York");

print $date->strftime("%Y%m%d %H:%M %Z")."\n";

使用Date::Parse来解析时间
use Date::Parse;
use POSIX;

$orig = "20090103 12:00";

print strftime("%Y%m%d %R", localtime(str2time($orig, 'GMT')));
You can also use Time::ParseDate and parsedate() instead of Date::Parse and str2time(). Note that the de facto standard atm. seems to be DateTime (but you might not want to use OO syntax just to convert a timestamp).

使用DateTime来解析时间
use DateTime;
$dt=DateTime->new(
year=>1984,
month=>10,
day=>16,
hour=>16,
minute=>12,
second=>47,
nanosecond=>500000000,
time_zone=>'Asia/Shanghai',
);

#从unix时间戳进行转换
$dt=DateTime->from_epoch(epoch=>$epoch);
$dt=DateTime->now;#sameas(epoch=>time())


使用Time::Piece来解析时间

perl -MPOSIX -e 'print strftime "%Z (%z)\n",localtime'
CST (+0800)

向Time::Piece对象传入参数是通过strptime函数来实现的,传入后函数内部会将其按gmt时间来处理。处理代码如下:
use Time::Piece;

#想处理的日期时间(当地)
my $date = '2013-11-09 9:00';

# Parse the date using strptime(), which uses strftime() formats.将其按相关的格式传入strptime函数
my $time = Time::Piece->strptime($date, "%Y-%m-%d %k:%M");

# 打印出为gmt的日期时间
say $time->datetime;

# Get your local time zone offset.得到时区与gmt的关系后并处理为当地日期时间
$time -= $time->localtime->tzoffset;

# And here it is localized.现在得到的就是本地日期时间,如果取出时戳的话,就是当地时间的时戳
say $time->datetime;