As already mentioned, the Date::Calc module will do the trick. Specifically, look at the Decode_Date_US and Decode_Date_EU functions for parsing out the day, month, and year. Unless I'm mistaken, though, you'll have to employ something like sprintf to format the date. There is also the check_date function to verify the date is valid.
In the spirit of TMTOWTDI, though, you could also use the Date::Manip module. It has different strengths than Date::Calc, and it might be useful for other projects. Here is how you could do this using Date::Manip:
use strict;
use warnings;
use Date::Manip;
my $rawdate = '10/12/04';
Date_Init( "DateFormat = US" ); # default
munge_date( $rawdate );
Date_Init( "DateFormat = European" );
munge_date( $rawdate );
$rawdate = '32/12/04';
munge_date( $rawdate );
sub munge_date
{
my ( $rawdate ) = @_;
my %cfgvars = map { split( '=', $_ ) } Date_Init();
print "DateFormat is set to $cfgvars{DateFormat}, ",
"parsing $rawdate:\n";
my $date = DateCalc( $rawdate, "+ 1 week" );
if( not defined $date )
{
print " $rawdate is not a valid date\n";
return;
}
print ' orig date = ', UnixDate( $rawdate, "%b %e, %Y" ), "\n";
print ' + 1 week = ', UnixDate( $date, "%m/%d/%y" ),
" (mm/dd/yy)\n";
print ' ', UnixDate( $date, "%d/%m/%y" ),
" (dd/mm/yy)\n";
print ' ', UnixDate( $date, "%Y-%m-%d" ),
" (yyyy-mm-dd)\n";
}
** OUTPUT **
DateFormat is set to US, parsing 10/12/04:
orig date = Oct 12, 2004
+ 1 week = 10/19/04 (mm/dd/yy)
19/10/04 (dd/mm/yy)
2004-10-19 (yyyy-mm-dd)
DateFormat is set to European, parsing 10/12/04:
orig date = Dec 10, 2004
+ 1 week = 12/17/04 (mm/dd/yy)
17/12/04 (dd/mm/yy)
2004-12-17 (yyyy-mm-dd)
DateFormat is set to European, parsing 32/12/04:
32/12/04 is not a valid date
If you use Date::Manip, make sure to set a default value for the timezone variable. If the timezone cannot be determined automatically, you'll get an error.
|