将GMT中的时间转换为perl中的当前时区

时间:2014-11-05 01:44:10

标签: perl

我想将GMT时间字符串转换为我的系统时区。 防爆。 Tue Nov 04 2014年2月22日03:03 GMT

我的机器时区是PST,因此输出应为:2014-11-04 14:03:03 PST

我可以在bash中执行此操作但无法找到perl的任何解决方案。

Bash solution => timestamp_local = date "+%Y-%m-%d %H:%M:%S %Z" -d "$timestamp_GMT"

任何人都有perl解决方案吗?

PS:我必须处理一个巨大的文件(大约100-200MB的文本文件)。所以,我想要一个优化的解决方案。

2 个答案:

答案 0 :(得分:3)

使用DateTime和朋友足够简单。

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use DateTime::Format::Strptime;
use DateTime;

my $format = '%a %b %d %H:%M:%S %Y %Z';
my $time_string = 'Tue Nov 04 22:03:03 2014 GMT';

my $dt_p = DateTime::Format::Strptime->new(
  pattern => $format,
  time_zone => 'UTC',
);

my $time = $dt_p->parse_datetime($time_string);

say $time->strftime('%a %b %d %H:%M:%S %Y %Z');

$time->set_time_zone('America/Los_Angeles');

say $time->strftime('%a %b %d %H:%M:%S %Y %Z');

更新: this old answer显示了如何与核心模块Time :: Piece非常相似。

答案 1 :(得分:1)

POSIX库应该足以做到这一点;

use strict;
use feature qw/say/;
use POSIX qw(strftime tzset);

say strftime("%Y %d %m %H:%M:%S GMT", gmtime(time));    # GMT
say strftime("%Y %d %m %H:%M:%S %Z", localtime(time));  # Local Time

# Set to  custom timezone
$ENV{TZ} = 'America/Los_Angeles';
tzset;
say strftime("%Y %d %m %H:%M:%S %Z", localtime(time));  # Custom Zone