日期转换
问题描述:
在Perl中,我怎么转换日期像日期转换
Thu Mar 06 02:59:39 +0000 2008
到
2008-03-06T02:59:39Z
尝试HTTP ::日期,如果这个问题没有在字符串中+0000它工作:(
答
DateTime::Format::Strptime将执行此转换。
#!/usr/bin/perl
use strict;
use warnings;
use 5.012;
use DateTime::Format::Strptime;
my $date = 'Thu Mar 06 02:59:39 +0000 2008 ';
my(@strp) = (
DateTime::Format::Strptime->new(pattern => "%a %b %d %T %z %Y",),
DateTime::Format::Strptime->new(pattern => "%FY%T%Z",)
);
my $dt = $strp[0]->parse_datetime($date);
print $strp[1]->format_datetime($dt);
打印2008-03-06T02:59:39UTC
克里斯
答
所以,用一个正则表达式编辑和使用HTTP::Date
:
(my $new_date_string = $old_state_string) =~ s/[+-]\d{4,}\s+//;
答
如果你绝对,积极确保日期将始终以这种格式,你可以简单地使用正则表达式重新格式化它。唯一的问题是你必须有一种将月份转换为数字的方式。这样,您就不必下载任何额外的模块来做日期转换:
my $date = "Thu Mar 06 02:59:39 +0000 2008"; #Original String
#Create the Month Hash (you might want all twelve months).
my %monthHash (Jan => "01", Feb => 2, Mar => 3);
# Use RegEx Matching to parse your date.
# \S+ means one or more non-spaces
# \s+ means one or more spaces
# Parentheses save that part of the string in $1, $2, $3, etc.
$date =~ m/\S+\s+(\S+)\s+(\S+)\s+(\S+)\s+\S+\s(.*)/;
my $monthString = $1;
my $day = $2;
my $time = $3;
my $year = $4;
# Convert Month string to a number.
my $month = $monthHash{$monthString};
#Reformat the string
$fmtDate="$year-$month-$day" . "T" . "$time" . "Z";
否则我会说,你也可以尝试日期时间::格式:: Strptime,但Chris Charley打我吧。
您也可以使用Time :: Piece,因为它自V 5.10开始在CORE perl发行版中。 – 2011-05-04 21:11:11