anon
anon

Reputation:

How can I validate dates in Perl?

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

Upvotes: 6

Views: 10505

Answers (3)

draegtun
draegtun

Reputation: 22560

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!

Upvotes: 10

anon
anon

Reputation:

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

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

Upvotes: 0

brian d foy
brian d foy

Reputation: 132812

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, :)

Upvotes: 9

Related Questions