Reputation: 609
In my program I have the user input a date in the format of "Month Day" (example May 25) and I want to be able to print an error message if it is an invalid date (example February 30).
So here's some code
$start_date = ARGV[0];
my $year = DateTime->now->year; # adds a year to the date
my $date_parser = DateTime::Format::Strptime->new(pattern => '%Y %B %d', # YYYY Month DD
);
my $start_epoch = $date_parser->parse_datetime("$year $start_date")->epoch();
Right after this I need some kind of if statement right?
Upvotes: 1
Views: 1836
Reputation: 1205
From perlmonks:
use Time::Local; my $date = ' 19990230'; # 30th Feb 1999 $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 + 1; } or print "Bad date: $@";
This should do you justice
Upvotes: 0
Reputation: 53478
If the date is invalid, then the parser will return undef
. You will see this quite quickly if you do:
my $start_date = "Feb 30";
my $year = DateTime->now->year; # adds a year to the date
my $date_parser = DateTime::Format::Strptime->new(pattern => '%Y %B %d', # YYYY Month DD
);
my $start_epoch = $date_parser->parse_datetime("$year $start_date")->epoch();
The solution:
my $parsed = $date_parser->parse_datetime("$year $start_date");
if ( not defined $parsed ) { print "Error - invalid date\n"; }
Upvotes: 3