我用过localtime Perl 中的函数来获取当前日期和时间,但需要解析现有日期。我有以下格式的 GMT 日期:“20090103 12:00”我想将其解析为我可以使用的日期对象,然后将 GMT 时间/日期转换为我当前的时区,该时区目前是东部标准时间.因此,我想将“20090103 12:00”转换为“20090103 7:00”任何有关如何执行此操作的信息将不胜感激。
最佳答案
因为 Perl 内置的日期处理接口(interface)有点笨重,而且你最终会传递大约六个变量,所以更好的方法是使用 DateTime或 Time::Piece . DateTime 是全能歌唱、全能跳舞的 Perl 日期对象,您可能最终会想要使用它,但 Time::Piece 更简单且完全适合此任务,具有与 5.10 一起发布的优势,并且该技术是两者基本相同。
这是使用 Time::Piece 和 strptime 的简单灵活的方法.
#!/usr/bin/perl
use 5.10.0;
use strict;
use warnings;
use Time::Piece;
# Read the date from the command line.
my $date = shift;
# Parse the date using strptime(), which uses strftime() formats.
my $time = Time::Piece->strptime($date, "%Y%m%d %H:%M");
# Here it is, parsed but still in GMT.
say $time->datetime;
# Create a localtime object for the same timestamp.
$time = localtime($time->epoch);
# And here it is localized.
say $time->datetime;
为了对比,这是手动方式。
由于格式是固定的,正则表达式就可以了,但如果格式发生变化,您将不得不调整正则表达式。
my($year, $mon, $day, $hour, $min) =
$date =~ /^(\d{4}) (\d{2}) (\d{2})\ (\d{2}):(\d{2})$/x;
然后将其转换为 Unix 纪元时间(自 1970 年 1 月 1 日以来的秒数)
use Time::Local;
# Note that all the internal Perl date handling functions take month
# from 0 and the year starting at 1900. Blame C (or blame Larry for
# parroting C).
my $time = timegm(0, $min, $hour, $day, $mon - 1, $year - 1900);
然后回到你的本地时间。
(undef, $min, $hour, $day, $mon, $year) = localtime($time);
my $local_date = sprintf "%d%02d%02d %02d:%02d\n",
$year + 1900, $mon + 1, $day, $hour, $min;
关于perl - 如何在 Perl 中解析日期和转换时区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/411740/