astroboy has asked for the wisdom of the Perl Monks concerning the following question:

Hi

There ae a number of posts on this site on how to validate dates - and they seems to be based on the notion that the date format is known in advance (e.g. checking for valid date).

I have a slightly different situation. I need to validate dates in any number of different files, which can have dates in a number of different formats. I know the posix date format of each date field (e.g. '%d/%m/%Y'), so I have been doing this

my $strp = DateTime::Format::Strptime->new(pattern => $pattern); ... my $dt = $strp->parse_datetime($value) || <handle error>;

Of course, creating a DateTime object for each field a validate is quite expensive, and it takes too long to run this even a moderately sized file. Does anyone know of another routine that can validate a date against a posix format? Note I can't use something like Date::Manip to intuit the date, because it can't handle some of my cases(d/m/y v m/d/y), whereas the posix string can be used to explicitly state the format.

Thanks

Replies are listed 'Best First'.
Re: Fast way to validate dates
by astroboy (Chaplain) on Jun 04, 2009 at 23:16 UTC
    Hmmm, no matter how long I spend researching an issue before I post it on SoW, I tend to discover it straight away once I've submitted the question. The answer is POSIX::strptime.
Re: Fast way to validate dates
by Your Mother (Archbishop) on Jun 05, 2009 at 05:35 UTC

    Here is a slightly goofy proof of concept in another direction.

    use Date::Calc qw( check_date ); while ( <DATA> ) { chomp; my @date = ( /(\d+)/g )[2,0,1]; print and print check_date(@date) ? "-->Yep\n" : "-->Nope\n"; } __END__ 1.1.1 6/4/1989 2-29-2000 2/29/2001

    I don't know how it compares to strptime but Date::Calc is extremely fast so if it's important, it might be worth benchmarking. Correctly rearranging the DMY and accounting for YYYY (e.g., I believe /01 would be interpreted as 1 CE) would be part of the implementation as DC only accepts Y{1,4}, M?M, D?D.