1

Want to convert for example that date:

02082012

In that case:
02 - Day
08 - Month
2012 - Year

For now I separate the date but not able to convert into month:

#echo "02082012"|gawk -F "" '{print $1$2 "-" $3$4 "-" $5$6$7$8}'
#02-08-2012

Expected view after convert and to catch all Months:

02-Aug-2012
4

6 回答 6

3

直截了当:

kent$ date -d "$(echo '02082012'|sed -r 's/(..)(..)(....)/\3-\2-\1/')" "+%d-%b-%Y"
02-Aug-2012
于 2013-07-04T12:32:54.237 回答
3

POSIX模块的另一个 Perl 解决方案,它位于 Perl 核心中。

use POSIX 'strftime';

my $date = '02082012';
print strftime( '%d-%b-%Y', 0, 0, 0,
  substr( $date, 0, 2 ),
  substr( $date, 2, 2 ) - 1,
  substr( $date, 4, 4 ) - 1900 );

查看http://strftime.net/以获得关于占位符要做什么的非常好的概述strftime

于 2013-07-04T12:37:32.207 回答
2

Time::Piece是一个核心 Perl 模块,非常适合像这样的简单操作。

#!/usr/bin/perl

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

my $string = '02082012';

my $date = Time::Piece->strptime($string, '%d%m%Y');

say $date->strftime('%d-%b-%Y');

(是的,这与 user1811486 的答案非常相似 - 但它使用原始问题中要求的正确格式。)

于 2013-07-04T15:45:12.997 回答
2

使用 Perl 的 POSIX 模块,strftime看起来像

#! /usr/bin/env perl

use strict;
use warnings;

use POSIX qw/ strftime /;

while (<>) {
  chomp;

  if (my($d,$m,$y) = /^(\d\d)(\d\d)(\d\d\d\d)$/) {
    print strftime("%d-%b-%Y", 0, 0, 0, $d, $m-1, $y-1900), "\n";
  }
}

输出:

$回声02082012 | 转换日期
2012 年 8 月 2 日
于 2013-07-04T12:42:45.927 回答
1

要拆分具有固定字段长度的字符串,请使用unpack

my $input = "02082012";
my ( $day, $month, $year ) = unpack( 'a2 a2 a4', $input );
print "$input becomes $day, $month, $year\n";

请参阅http://perldoc.perl.org/functions/unpack.html

然后,如其他答案中所述,用于POSIX::strftime()重新格式化日期。

于 2013-07-04T13:47:26.213 回答
1

我是这样想的......

use 5.10;
use strict;
use warnings;
use Time::Piece;
my $date = '2013-04-07';
my $t = Time::Piece->strptime($date, '%Y-%m-%d');
print $t->month;
print $t->strftime('%Y-%b-%d');

只是我试过这个...

于 2013-07-04T12:35:42.767 回答