How can I change the date formats in Perl?

2020-02-02 00:22发布

I just want to convert the dates from 20111230 format to 30-dec-2011.

标签: perl
5条回答
混吃等死
2楼-- · 2020-02-02 00:31

Here is another solution. It uses DateTimeX::Easy:

#!/usr/bin/env perl

use strict;
use warnings;

use DateTimeX::Easy;

my $dt = DateTimeX::Easy->parse('20111230');
print lc $dt->strftime('%d-%b-%G');
查看更多
欢心
3楼-- · 2020-02-02 00:33

One way is to use Date::Simple:

use warnings;
use strict;
use Date::Simple qw(d8);

my $d = d8('20111230');
print $d->format('%d-%b-%Y'), "\n";

__END__

30-Dec-2011
查看更多
你好瞎i
4楼-- · 2020-02-02 00:53

In keeping with TMTOWTDI, you can use Time::Piece

#!/usr/bin/env perl
use strict;
use warnings;
use Time::Piece;
my $t = Time::Piece->strptime("20111230", "%Y%m%d");
print $t->strftime("%d-%b-%Y\n");
查看更多
走好不送
5楼-- · 2020-02-02 00:53

If I can't use one of the date modules, POSIX isn't so bad and it comes with perl:

use v5.10;
use POSIX qw(strftime);

my $date = '19700101';

my @times;
@times[5,4,3] = $date =~ m/\A(\d{4})(\d{2})(\d{2})\z/;
$times[5] -= 1900;
$times[4] -= 1;

# strftime(fmt, sec, min, hour, mday, mon, year, wday = -1, yday = -1, isdst = -1)
say strftime( '%d-%b-%Y', @times );

Making @times is a bit ugly. You can't always get what you want, but if you try sometimes, you might find you get what you need.

查看更多
【Aperson】
6楼-- · 2020-02-02 00:54

A quick solution.

my $date = '20111230';
my @months = (
    'Jan','Feb','Mar','Apr',
    'May','Jun','Jul','Aug','Sep',
    'Oct','Nov','Dec'
);

if($date =~ m/^(\d{4})(\d{2})(\d{2})$/){
        print $3 . '-' . $months[$2-1] . '-' . $1;
}
查看更多
登录 后发表回答