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

Hi monks, I am using Time::Piece module in my application. If i pass invalid date "31-02-2007' with in strftime method i didn't get error. If i passed the invalid date i need to know whether the date is valid or not using Time::Piece module or using someother module. Please provide some sample codes or ideas.
  • Comment on How to check the valid date using Time::Piece module?

Replies are listed 'Best First'.
Re: How to check the valid date using Time::Piece module?
by liverpole (Monsignor) on Jan 24, 2007 at 20:42 UTC
    Personally, I'd use Date::Calc, which has given me good results in the past.

    Here's a small program showing how you could pass a date string as dd-mm-yyyy, parse it into the corresponding day, month, and year, and test it with Date::Calc::check_date:

    use strict; use warnings; use Date::Calc qw/check_date/; check_this("28-02-2007"); check_this("31-02-2007"); sub check_this { my ($date) = @_; if ($date !~ /^(\d+)-(\d+)-(\d+)$/) { printf "Invalid date '$date'\n"; return; } my ($day, $mon, $yr) = ($1, $2, $3); my $result = check_date($yr, $mon, $day); printf "Result for '$date' => %s\n", $result? "Okay": "Bad"; }

    The output is:

    Result for '28-02-2007' => Okay Result for '31-02-2007' => Bad

    Update:  Fixed mistyped method name.


    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
Re: How to check the valid date using Time::Piece module?
by graff (Chancellor) on Jan 25, 2007 at 05:28 UTC
    If you happen to be dealing only with dates "since the epoch", you can convert the "untrusted" date string to seconds since the epoch, then convert back to a date string of the same format.

    A variety modules (e.g. Time::Local) can be used convert from "month, day, year" (and "hour, minute") values to seconds since the epoch (i.e. "unix seconds"), and they can be fairly tolerant about numeric values that are out-of-range (e.g. a day value of 32, or Feb. 30, or an hour value of 26).

    But when converting from seconds back to month, day, year, hour, minute (e.g. using localtime), you will always get a valid date. So if the input string does not match the output string, the input must have been invalid in some way.

Re: How to check the valid date using Time::Piece module?
by lin0 (Curate) on Jan 24, 2007 at 20:37 UTC
Re: How to check the valid date using Time::Piece module?
by Anonymous Monk on Jan 24, 2007 at 20:34 UTC
    For the above..question..same added $perl -e 'use Time::Piece; print Time::Piece->strptime("2006-02-31", "%Y-%m-%d");' will give you some date but $perl -e 'use Time::Piece; print Time::Piece->strptime("2006-02-32", "%Y-%m-%d");' will throw error. That is, anything less than 32 accepts as valid day.