比较两个Time :: Piece对象

时间:2019-07-03 06:01:57

标签: perl comparison

我尝试了Time :: Piece和Time :: Seconds包,并编写了以下脚本来比较两个Time :: Piece对象。我正在尝试确定当前的当前时间是在一天中的特定时间之前还是之后。在这种情况下,我将特定时间设置为10:30:00。

我打印了两个Time :: Piece值,从中看来代码应该可以工作,但是结果出乎我的意料。

有人可以看到我的代码有什么问题吗?

use strict;
use warnings;
use Time::Piece;
use Time::Seconds;

my $settDate;
my $time = Time::Piece->new;
my $eod  = Time::Piece->strptime($time->date . "T10:30:00", '%Y-%m- %dT%H:%M:%S');
print "Time is: ${time}, EOD is: ${eod}\n";
if ($time > $eod) {
    print "Yes, we've passed EOD.\n";
    $settDate = $time->strftime('%Y/%m/%d');
} else {
    print "No, we haven't passed EOD yet\n";
    $settDate = ($time - ONE_DAY)->strftime('%Y/%m/%d');
}
print "Default date is: ${settDate}\n";

输出显示:

Time is: Wed Jul  3 15:44:26 2019, EOD is: Wed Jul  3 10:30:00 2019
No, we haven't passed EOD yet
Default date is: 2019/07/02

1 个答案:

答案 0 :(得分:0)

意外的比较结果可能是由于$time$eod中的时区偏移不同-Time::Piece->new产生了本地时间,而{{1} }产生UTC。
最简单的解决方法是始终使用UTC:将Time::Piece->strptime替换为Time::Piece->new