【问题标题】:perl "DateTime" module print wrong timeperl "DateTime" 模块打印错误时间
【发布时间】:2021-05-09 18:55:04
【问题描述】:

我正在使用DateTime 模块。但是它提供了错误的时间。请考虑以下代码:

#!/usr/bin/perl -w
use strict;

use Time::localtime;
my $now = ctime();
print $now."\n";

print "------------------------------\n";

use DateTime;
my $dt = DateTime->now;
print $dt."\n";

它的输出是:

Wed Dec 26 22:11:52 2012
------------------------------
2012-12-27T06:11:52

所以,如您所见,DateTime 输出领先 8 小时,这是错误的。这是 Linux date 命令输出:

# date
Wed Dec 26 22:13:17 PST 2012

因此,date 命令输出与time::localtime 输出匹配。

您能否帮助我了解我在使用 DateTime 模块时哪里出错了。

-谢谢。

更新:

来自 hte CPAN 文档:

DateTime->now( ... )

This class method is equivalent to calling from_epoch() with the value returned from Perl's time() function. Just as with the new() method, it accepts "time_zone" and "locale" parameters.

By default, the returned object will be in the UTC time zone.

所以,返回的时间似乎是 UTC。但是,我在 PST 所在的时区。可能这就是为什么我看到不同的时间。

【问题讨论】:

  • 我假设您在太平洋时区?你需要告诉 DateTime 你想要什么时区。
  • 是的,我刚刚更新了我的帖子。它返回 UTC 时间。进一步阅读以了解如何传递时区信息。谢谢。
  • 您刚刚学习了时区的第一课。从今以后,当时间与您的预期不符时,您首先会想到的是检查时区。
  • 是的,没错。谢谢。
  • 这些人“纠正”你错了。用户没有理由知道机器所在的时区。

标签: perl


【解决方案1】:

我通过了区域信息,它现在可以正常工作了:

#!/usr/bin/perl -w
use strict;

use Time::localtime;
my $now = ctime();
print $now."\n";

print "------------------------------\n";

use DateTime;
my $dt = DateTime->now ( time_zone => 'America/Los_Angeles' );
print $dt."\n";

输出:

Wed Dec 26 22:28:44 2012
------------------------------
2012-12-26T22:28:44

东海岸

my $dateF = DateTime->now( time_zone => 'America/New_York' )->ymd;

【讨论】:

    【解决方案2】:

    用户没有理由知道机器的时区,即使他们知道,硬编码也是个坏主意。答案是

    my $dt = DateTime->now(time_zone => 'local') # current time, local timezone
    my $dt = DateTime->from_epoch(epoch=>time(), time_zone=>'local') # from timestamp
    

    这会将其设置为机器的时区。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-26
      • 2017-01-21
      • 2020-04-21
      • 1970-01-01
      • 2011-12-25
      相关资源
      最近更新 更多