我正在尝试相对于当前本地时间进行一些日期计算。例如:
use feature qw(say);
use strict;
use warnings;
use Time::Piece;
my $fmt = '%Y-%m-%d_%H:%M:%S';
my $timestamp = "2015-04-12_11:07:27";
# This gives incorrect $t1 relative to localtime
my $t1 = Time::Piece->strptime( $timestamp, $fmt );
my $t2 = localtime;
say "Local time: " . localtime;
say "Local time epoch: " . time;
say $t1->epoch();
say $t2->epoch();
my $timestamp1 = $t1->strftime( $fmt );
my $timestamp2 = $t2->strftime( $fmt );
say $timestamp1;
say $timestamp2;
my $delta = $t2 - $t1;
say $delta;
样本输出:
Local time: Sun Apr 12 12:21:49 2015
Local time epoch: 1428834109
1428836847
1428834109
2015-04-12_11:07:27
2015-04-12_12:21:49
-2738
这显然会导致错误的时差-2738。(它应该是一个正数)
如果您解析的日期时间没有时区信息,则假定为UTC。您可以通过在脚本中添加以下两行来看到这一点:
say "tzo1 = ",$t1->tzoffset;
say "tzo2 = ",$t2->tzoffset;
在巴黎,以上输出如下:
tzo1 = 0
tzo2 = 7200
您可以使用未记录的功能来localtime
代替使用默认值作为本地时区,而是将其替换为本地时区Time::Piece
。
$ perl -MTime::Piece -E'
say Time::Piece->strptime("2015-04-12_11:07:27", "%Y-%m-%d_%H:%M:%S")->tzoffset;
say localtime ->strptime("2015-04-12_11:07:27", "%Y-%m-%d_%H:%M:%S")->tzoffset;
'
0
7200
进行较小的更改即可得到您期望的答案。
$ perl -MTime::Piece -E'
say localtime->strptime("2015-04-12_11:07:27", "%Y-%m-%d_%H:%M:%S") - localtime;
'
5524
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句