I know others have already posted their versions, but here is my attempt at a data-driven implementation. It allows alternative delimiters, but requires that the chosen delimiter is the same throughout the date expression. If you want to validate the incoming date before choosing a format, you should use
Date::Manip or something similar.
#!/usr/bin/perl
use strict;
use warnings;
my %Pattern = ( '(\d{1,2})([-\/.])(\d{1,2})\2(\d{2})' => 'MM%sDD%sRR
+',
'(\d{1,2})([-\/.])(\d{1,2})\2(\d{4})' => 'MM%sDD%sYY
+YY',
'(\d{4})([-\/.])(\d{1,2})\2(\d{1,2})' => 'YYYY%sMM%s
+DD'
);
sub ChooseDateFmt($)
{
my $datestr = shift or die;
for my $p (keys %Pattern)
{ return sprintf($Pattern{$p}, $2, $2) if $datestr =~ /^\s*$p\
+s*$/; }
}
while (<DATA>)
{
chomp;
print "Date\t$_\tFormat=" . ChooseDateFmt($_) . "\n";
}
__DATA__
10/15/2006
2006/11/01
11/01/06
2006.11.01
11-01-06
Output:
Date 10/15/2006 Format=MM/DD/YYYY
Date 2006/11/01 Format=YYYY/MM/DD
Date 11/01/06 Format=MM/DD/RR
Date 2006.11.01 Format=YYYY.MM.DD
Date 11-01-06 Format=MM-DD-RR
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.