在我的程序中,我让用户输入日期格式为"月日" (例如5月25日)我希望能够在错误消息无效的情况下打印错误消息(例如2月30日)。
所以这里有一些代码
$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();
在此之后,我需要某种if语句吗?
答案 0 :(得分:3)
如果日期无效,则解析器将返回undef
。如果你这样做,你会很快看到这个:
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();
解决方案:
my $parsed = $date_parser->parse_datetime("$year $start_date");
if ( not defined $parsed ) { print "Error - invalid date\n"; }
答案 1 :(得分:0)
来自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: $@";
这应该是你的正义