simont
simont

Reputation: 72537

Convert string to date with DateTime::Format::Strptime

From this answer, I'm using DateTime::Format::Strptime to grab the date from a string.

I'm using the following pattern: %m%d%Y%n%T. This should be matching:

However, on input: [05/18/2011 14:14:05] it's failing with the error:

Your datetime does not match your pattern

As far as I can see, my pattern matches the input pattern. Where am I going wrong?

Relevant code is below:


use DateTime::Format::Strptime qw( );

my $format = DateTime::Format::Strptime->new(
   pattern   => '%m%d%Y%n%T',
   time_zone => 'local',
   on_error  => 'croak',
);

my $dt = $fields->[1] ;
print "Date:[$dt]\n";
my $dateopen = $format->parse_datetime($dt);

Output:

Date:[05/18/2011 14:14:05]
Your datetime does not match your pattern

Upvotes: 2

Views: 6397

Answers (1)

user507077
user507077

Reputation:

The non-pattern characters are important as well. You have slashes between your date components, hence the pattern '%m/%d/%Y%n%T' works while yours doesn't.

Note that the pattern %D would not work either as it is a shortcut for %m%d%Y and doesn't include the slashes either.

Upvotes: 5

Related Questions