Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Date module laziness

by bobf (Monsignor)
on Dec 05, 2004 at 06:12 UTC ( [id://412463]=note: print w/replies, xml ) Need Help??


in reply to Date module laziness

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://412463]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (8)
As of 2024-04-25 11:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found