Validating date in yyyymmdd format using PERL

Hi all,

i had a code where in user will enter a date in yyyymmdd format.. i didnt use any validation for the date and now the problem is if a user enters date instead of month after year it is proceeding with the code..

like if the date is

20120426

and if the user enters

20122604

it should not proceed!

so i need to have a check for the same.. pls help

/^20\d\d(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$/

Beware, this regex will still validate if date entered is 20120231.

hi bala,

thanks for your quick reply...

if my variable is $date then how to use this... i am beginner in perl. pls help

---------- Post updated at 02:53 AM ---------- Previous update was at 02:52 AM ----------

and this only validates for year 2012 or can i also use 1998 or something like?

 
$ cat one.pl
#!/bin/perl
use Time::Local;
my $date = $ARGV[0];
$date =~ s/\s+$//;
$date =~ s/^\s*//;
my ($year, $month, $day) = unpack "A4 A2 A2", $date;
eval{ 
    timelocal(0,0,0,$day, $month-1, $year); # dies in case of bad date
    print "$date is valid\n";
} or print "Bad date: $@";

bash-3.2$ perl one.pl 20120430
20120430 is valid

bash-3.2$ perl one.pl 20120431
Bad date: Day '31' out of range 1..30 at one.pl line 8

bash-3.2$ perl one.pl 20120231
Bad date: Day '31' out of range 1..29 at one.pl line 8

bash-3.2$ perl one.pl 20120229
20120229 is valid

bash-3.2$ perl one.pl 20120230
Bad date: Day '30' out of range 1..29 at one.pl line 8
4 Likes

nice one itkamaraj