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

I have a string of the form "YYYY-MM-DD HH:mm:ss". Does anyone know how I can check this to see if it is in the correct format and also a valid date & time?

Replies are listed 'Best First'.
Re: datetime verify
by BazB (Priest) on Jan 31, 2003 at 22:02 UTC
    use Date::Calc;

    If the information in this post is inaccurate, or just plain wrong, don't just downvote - please post explaining what's wrong.
    That way everyone learns.

Re: datetime verify
by poj (Abbot) on Jan 31, 2003 at 23:31 UTC
    Like this
    use strict; use Date::Calc qw(check_date check_time); =head1 Date::Calc functions if (check_date($year,$month,$day)) This function returns "true" ("1") if the given three numerical values + "$year", "$month" and "$day" constitute a valid date, and "false" (" +0") otherwise. if (check_time($hour,$min,$sec)) This function returns "true" ("1") if the given three numerical values + "$hour", "$min" and "$sec" constitute a valid time (0 <= $hour < 24, + 0 <= $min < 60 and 0 <= $sec < 60), and "false" ("0") otherwise. =cut # test routine while (<DATA>){ chomp; my $ok = check($_) ? "valid" : "NOT valid"; print "$_ is $ok\n"; } # check valid date time YYYY-MM-DD hh:mm:ss sub check { my $dt = shift; if ($dt =~ m!^(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$!){ return ( check_date($1,$2,$3) && check_time($4,$5,$6) ); } else { return 0; } } __DATA__ 2001-01-01 12:12:12 2001-02-29 12:12:12 2004-02-29 12:12:12 2001-01-01 25:12:12 2001-01-01 12:61:12 2001-01-01 12:12:61 01-01-2001 12:12:12
    poj
Re: datetime verify
by phydeauxarff (Priest) on Jan 31, 2003 at 22:08 UTC
    I suppose you could use Date::Parse to check to see if you get a valid Unix Timestamp.
    If you want to have the date entered in any format and converted to what you describe you might take a look at Date::Manip, though that module is pretty big.
Re: datetime verify
by OM_Zen (Scribe) on Feb 01, 2003 at 04:34 UTC
    Hi ,

    The Data::Calc is used to check_dates