Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, how can I ensure that a string corresponds to a valid date?

I was wondering if there is a simple way in Perl to ensure that a date string corresponds to a valid date.

For example, 2012 02 30 is incorrect because it doesn't exist.

like image 324
Gordon Avatar asked Feb 24 '12 14:02

Gordon


1 Answers

The DateTime module will validate dates when creating a new object.

$ perl -we 'use DateTime; my $dt; 
    eval { $dt = DateTime->new( 
        year => 2012, 
        month => 2, 
        day => 30);
    }; print "Error: $@" if $@;'

Error: Invalid day of month (day = 30 - month = 2 - year = 2012) at -e line 1

It also works dynamically on a given DateTime object:

$dt->set(day => 30);
like image 157
TLP Avatar answered Sep 22 '22 12:09

TLP