【问题标题】:Comparing two Time::Piece objects比较两个 Time::Piece 对象
【发布时间】:2019-07-03 16:25:55
【问题描述】:

我尝试了 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

【问题讨论】:

  • 什么 perl 版本?你的当地时间是哪个时区?
  • 我的 perl 版本是 5.20。活动 Perl。我通过在 Time::Piece->strptime. 中指定时区解决了我的问题

标签: perl comparison


【解决方案1】:

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

【讨论】:

  • 您还可以通过从本地时间对象(它是kind of a hack)调用 strptime 在本地时间工作:my $time = localtime->strptime(...)
  • 好点!我只是注意到这不适用于相当老的Time::Piece->VERSION,例如。 G。 1.15;它适用于 e。 G。 1.20_01.
  • 你说得对。就像你说的那样。我昨天晚些时候解决了这个问题,但没有机会回到这里发布更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-02
  • 2014-01-26
  • 2012-08-17
  • 2014-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多