使用核心模块在perl中使用正确的时区解析日期

时间:2014-11-27 11:29:45

标签: perl datetime

我必须对从数据库中读取的日期进行多次检查。 例如,我必须将它们与perl脚本的本地时间进行比较。 我还必须确定解析日期的日历日期。 为了拥有可读代码,我希望在生成的(localtime)和解析的(strptime)时间对象中都有相同的时区信息。

解决方案应该只有1个文件,因此任务应该只使用核心perl模块(版本5.10)。所以DateTime模块似乎不是一个选项。

我最接近的是Time::Piece,但似乎无法通过解析获得与Time::Piece::localtime()获得的时间对象相同的时间对象。

use Time::Piece;
use strict;
use warnings;
use 5.010;

sub mystrptime1 {
    my $datestr = shift;
    my $tzoffset = sprintf '%+03d00', localtime->tzoffset->hours;
    my $t = Time::Piece->strptime("$datestr $tzoffset", '%Y%m%d %H:%M:%S %z');
}

sub mystrptime2 {
    my $datestr = shift;
    my $t = Time::Piece->strptime($datestr, '%Y%m%d %H:%M:%S');
    # it will be interpreted as GMT, so subtract the time zone offset :-(
    return $t - Time::Piece::localtime->tzoffset;
}

my $FORMAT = '%Y%m%d %H:%M:%S';

for my $strptime (\&mystrptime1, \&mystrptime2) {
    my $lt = Time::Piece::localtime();
    say "localtime is $lt, tz offset is ", $lt->tzoffset();

    my $str = $lt->strftime($FORMAT);
    say "str is $str";
    my $g = $strptime->( $str );

    say "parsed time is $g, tz offset is ", $g->tzoffset();

    say "time difference is: ", $lt-$g;
    say "hour difference is: ", $lt->hour - $g->hour;
}

我想要的是小时差和零时差,这似乎是不可能的。

1 个答案:

答案 0 :(得分:1)

我能够通过在localtime结果上调用strptime来解决这两个问题:

sub mystrptime1 {
    my $datestr = shift;
    my $tzoffset = sprintf '%+03d00', localtime->tzoffset->hours;
    my $t = Time::Piece->strptime("$datestr $tzoffset", '%Y%m%d %H:%M:%S %z');
    return Time::Piece::localtime($t->epoch);
}

sub mystrptime2 {
    my $datestr = shift;
    my $t = Time::Piece->strptime($datestr, '%Y%m%d %H:%M:%S');
    # it will be interpreted as GMT, so subtract the time zone offset :-(
    $t -= Time::Piece::localtime->tzoffset;
    return Time::Piece::localtime($t->epoch);
}