如何在Perl中更改日期时间格式?

时间:2014-11-21 05:14:31

标签: perl

我想将日期时间格式转换为我想要的格式。

如何将日期时间格式从2014年11月21日星期五15:04:32转换为2014-11-21 15:04:32?

感谢

2 个答案:

答案 0 :(得分:2)

Time::Piece多年来一直是Perl的核心。

使用strptime(字符串解析时间)来解析日期/时间字符串。

使用strftime(字符串格式时间)根据需要设置日期/时间格式。

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;
use Time::Piece;

# Formats are defined in "man strftime"
my $in_fmt  = '%a %b %d %Y %H:%M:%S';
my $out_fmt = '%Y-%m-%d %H:%M:%S';

my $in_date = 'Fri Nov 21 2014 15:04:32';

my $date = Time::Piece->strptime($in_date, $in_fmt);
my $out_date = $date->strftime($out_fmt);

say $out_date;

答案 1 :(得分:1)

my $str = 'Fri Nov 21 2014 15:04:32';
my @months =('jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec');
my ($day,$mon,$date,$year,$time) = split(' ',lc($str));
my %month_hash;
@month_hash{@months} = (1 .. 12);
print "$year-$month_hash{$mon}-$date $time";

尝试这种原始方法,但符合您的要求。使用date :: manip进行灵活使用