【发布时间】: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