Hi, you said:
unless there is a more efficient way of doing it
Unless you are working on your regexp-fu, I would suggest not using a regexp to parse dates. Efficiency extends to future readability of your code.
Just use DateTime::Format::Strptime to make a parser with the format you want and eval to see if the string parses into a DateTime object.
Here's an SSCCE that demonstrates:
use strict; use warnings;
use feature qw/ say state /;
use DateTime::Format::Strptime;
for ( <DATA> ) {
chomp;
say sprintf '%-24s: %s', $_, validate( $_ ) ? 'OK' : 'Not OK';
}
sub validate {
state $parser = DateTime::Format::Strptime->new(
pattern => '%F %T.%3N',
on_error => 'croak',
);
return eval { $parser->parse_datetime( @_ ); 1 };
}
__DATA__
2017-01-29 11:30:07.370
2017-01-29 11:30:07.000
2017-01-32 11:30:07.370
2017-01-29 11:30:07
foo bar
Edit: Or, declare the parser without the on_error attribute, and then you can use the DateTime object, if you can parse a date from your string. Presumably you want to use the date after you've found it.
my $str = '2017-01-29 11:30:07.370';
$parser = DateTime::Format::Strptime->new( pattern => '%F %T.%3N' );
if ( my $dt = $parser->parse_datetime( $str ) ) {
say "Interestingly, $str falls on a " . $dt->day_name;
} else {
say "$str is not a valid date";
}
Hope this helps!
The way forward always starts with a minimal test.
|