tags:

views:

1390

answers:

3

How can I validate date strings in Perl? I'd like to account for leap years and also time zones. Someone may enter dates in the following formats:

11/17/2008
11/17/2008 3pm
11/17/2008 12:01am
11/17/2008 12:01am EST
11/17/2008 12:01am CST
+7  A: 

CPAN has many packages for dealing with dates, such as DateTime and Date::Manip. To parse your date, the Date::Parse module in TimeDate might work (yes, there are both DateTime and TimeDate).

In general, whenever you need to do something in Perl, check CPAN. There's probably a module for it. Look at what's available and see what fits your situation.

Good luck, :)

brian d foy
A: 

I'll post my answers here as I come across them.

use Time::Local
 http://www.perlmonks.org/?node_id=642627

+6  A: 

I use DateTime::Format::DateManip for things like this. Using your dates....

use DateTime::Format::DateManip; 

my @dates = (
    '11/17/2008',
    '11/17/2008 3pm',
    '11/17/2008 12:01am',
    '11/17/2008 12:01am EST',
    '11/17/2008 12:01am CST',
);

for my $date ( @dates ) {
    my $dt = DateTime::Format::DateManip->parse_datetime( $date );
    die "Cannot parse date $date"  unless defined $dt;
    say $dt;
}

# no dies.. produced the following....
# => 2008-11-17T00:00:00
# => 2008-11-17T15:00:00
# => 2008-11-17T00:01:00
# => 2008-11-17T05:01:00
# => 2008-11-17T06:01:00

NB. I'm on GMT here!

/I3az/

draegtun