日期转换

时间:2011-05-04 17:33:09

标签: perl date

在perl中,如何转换日期,如

Thu Mar 06 02:59:39 +0000 2008

2008-03-06T02:59:39Z

尝试HTTP :: Date,如果问题在字符串中没有+0000,则它有效:(

3 个答案:

答案 0 :(得分:6)

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

克里斯

答案 1 :(得分:1)

因此,使用正则表达式编辑它并使用HTTP::Date

( my $new_date_string = $old_state_string ) =~ s/[+-]\d{4,}\s+//;

答案 2 :(得分:1)

如果你绝对肯定日期总是采用那种格式,你可以简单地使用正则表达式重新格式化它。唯一的事情是你必须有一种方法将月份转换为数字。这样,您不必下载任何额外的模块来进行日期转换:

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";

否则我会说你也可以尝试DateTime :: Format :: Strptime,但是Chris Charley打败了我。