How can I validate dates in Perl?

匿名 (未验证) 提交于 2019-12-03 01:22:02

问题:

How can I validate date strings in Perl? I'd like to account for leap years and also time zones. Someone may enter dates in the following formats:

 11/17/2008 11/17/2008 3pm 11/17/2008 12:01am 11/17/2008 12:01am EST 11/17/2008 12:01am CST 

回答1:

I use DateTime::Format::DateManip for things like this. Using your dates....

use DateTime::Format::DateManip;   my @dates = (     '11/17/2008',     '11/17/2008 3pm',     '11/17/2008 12:01am',     '11/17/2008 12:01am EST',     '11/17/2008 12:01am CST', );  for my $date ( @dates ) {     my $dt = DateTime::Format::DateManip->parse_datetime( $date );     die "Cannot parse date $date"  unless defined $dt;     say $dt; }  # no dies.. produced the following.... # => 2008-11-17T00:00:00 # => 2008-11-17T15:00:00 # => 2008-11-17T00:01:00 # => 2008-11-17T05:01:00 # => 2008-11-17T06:01:00 

NB. I'm on GMT here!



回答2:

CPAN has many packages for dealing with dates, such as DateTime and Date::Manip. To parse your date, the Date::Parse module in TimeDate might work (yes, there are both DateTime and TimeDate).

In general, whenever you need to do something in Perl, check CPAN. There's probably a module for it. Look at what's available and see what fits your situation.

Good luck, :)



回答3:

I'll post my answers here as I come across them.

use Time::Local
 http://www.perlmonks.org/?node_id=642627



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!