Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Re: How to check if a date exists ?

by james2vegas (Chaplain)
on Oct 18, 2012 at 10:23 UTC ( #999701=note: print w/replies, xml ) Need Help??

in reply to How to check if a date exists ?

Time::Piece (in core since 5.10) has strptime, which would throw an error on an invalid date, and if you do something like:
# no 29 feb 2001 my $dt = Time::Piece->strptime("2001-02-29", "%F"); # will return 2001-03-01 print $dt->strftime("%F");

Time::Piece will correct your date, and if you need to catch this happening, compare the output of strftime on that object to the original date string. Any invalid date will throw an error that you can catch with eval or one of the many exception catching modules.
my $dt = eval { Time::Piece->strptime("2001-04-32", "%F") } or warn "This is not a valid date ($@).\n";

Replies are listed 'Best First'.
Re^2: How to check if a date exists ?
by HJO (Acolyte) on Oct 18, 2012 at 11:10 UTC


    First of all thank you for your answer, secondly, you're saying that this module is in the core since 5.10, but I'm using Perl 5.8.8, so I still can use it but I have to install it first right ?

    And finally, could you please "validate" my code ? :

    my $s = '20121018'; my $date; eval { $date = Time::Piece->strptime("$s"); }; if ( $@ ) { die qq{Error : the date doesn't exist or is not like YYYYMMDD\ +n} } else {print qq{date OK\n}} ;


      You need a format, like "%Y%m%d" as the second parameter to strptime (I left that out in my earlier code, so my fault).

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://999701]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (6)
As of 2020-10-23 11:33 GMT
Find Nodes?
    Voting Booth?
    My favourite web site is:

    Results (238 votes). Check out past polls.