Reputation: 1120
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
Upvotes: 1
Views: 173
Reputation: 69314
Time::Piece is a core Perl module and is great for simple manipulations like this.
#!/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');
(Yes, this is very similar to user1811486's answer - but it uses the correct formats as requested in the original question.)
Upvotes: 2
Reputation: 3601
To break apart a string with fixed field lengths, use unpack
:
my $input = "02082012";
my ( $day, $month, $year ) = unpack( 'a2 a2 a4', $input );
print "$input becomes $day, $month, $year\n";
See http://perldoc.perl.org/functions/unpack.html
Then, as stated in the other answers, use POSIX::strftime()
to reformat the date.
Upvotes: 1
Reputation: 139631
Using Perl’s POSIX module and strftime
looks like
#! /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";
}
}
Output:
$ echo 02082012 | convert-date 02-Aug-2012
Upvotes: 2
Reputation: 54373
Another Perl sollution with the POSIX module, which is in the Perl core.
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 );
Look at http://strftime.net/ for a very nice overview of what the placeholders to strftime
do.
Upvotes: 3
Reputation: 1314
I think like this.....
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');
Just I tried this ...
Upvotes: 1
Reputation: 195209
straightforward:
kent$ date -d "$(echo '02082012'|sed -r 's/(..)(..)(....)/\3-\2-\1/')" "+%d-%b-%Y"
02-Aug-2012
Upvotes: 3