How can I validate a "yyyy-MM-dd'T'HH:mm:ssZ" date/timestamp in UTC with Perl?
Code开发者_如何学运维 would be nice but a point in the right direction is good as well.
CPAN? RegEx?
I've seen both ways
"yyyy-MM-dd'T'HH:mm:ssZ";
"yyyy-MM-ddTHH:mm:ssZ";
Ether is definitely on the right track with DateTime. Using DateTime, you can be sure that you have a time that actually exists, where something on Feb 29, 2000 might get by if you wrote the checks yourself.
Your format looks like an ISO8601 string. So, use DateTime::Format::ISO8601 to do your parsing.
use DateTime;
use DateTime::Format::ISO8601;
my $string = '2010-02-28T15:21:33Z';
my $dt = DateTime::Format::ISO8601->parse_datetime( $string );
die "Impossible time" unless $dt;
You could use other format modules, such as D::F::Strptime, but you will wind up recreating what ISO8601 formatter already does.
Depending on what you're doing, you might want to coerce your string into a DateTime object, e.g.:
use DateTime::Format::MySQL;
my $dt = DateTime::Format::MySQL->parse_datetime( '2003-01-16 23:12:01' );
Then you can easily output your time string in a different format, perform calculations with it, etc.
You didn't specify what is generating the string in that particular format, but there are DateTime::Format:: modules for a large number of input sources.
精彩评论