我在Perl中使用了localtime函数来获取当前日期和时间,但需要在现有日期中进行解析.我有以下格式的GMT日期:"20090103 12:00"我想将其解析为我可以使用的日期对象,然后将GMT时间/日期转换为我当前的时区,这是当前的东部标准时间.所以我想将"20090103 12:00"转换为"20090103 7:00"任何关于如何做到这一点的信息将不胜感激.
因为Perl内置的日期处理接口有点笨拙,你最终传递了六个变量,更好的方法是使用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;
这是一个使用DateTime及其strptime格式模块的示例.
use DateTime; use DateTime::Format::Strptime; my $val = "20090103 12:00"; my $format = new DateTime::Format::Strptime( pattern => '%Y%m%d %H:%M', time_zone => 'GMT', ); my $date = $format->parse_datetime($val); print $date->strftime("%Y%m%d %H:%M %Z")."\n"; $date->set_time_zone("America/New_York"); # or "local" print $date->strftime("%Y%m%d %H:%M %Z")."\n"; $ perl dates.pl 20090103 12:00 UTC 20090103 07:00 EST
use DateTime; my @time = (localtime); my $date = DateTime->new(year => $time[5]+1900, month => $time[4]+1, day => $time[3], hour => $time[2], minute => $time[1], second => $time[0], time_zone => "America/New_York"); print $date->strftime("%F %r %Z")."\n"; $date->set_time_zone("Europe/Prague"); print $date->strftime("%F %r %Z")."\n";
这就是我要做的......
#!/usr/bin/perl use Date::Parse; use POSIX; $orig = "20090103 12:00"; print strftime("%Y%m%d %R", localtime(str2time($orig, 'GMT')));
您也可以使用Time::ParseDate
而parsedate()
不是Date::Parse
和str2time()
.请注意事实上的标准atm.似乎是DateTime(但您可能不想仅使用OO语法来转换时间戳).