Search code examples
perldatetimedatetime-formatstrptime

strptime incorrect output with input date


I'm trying to convert a string into a dt object, as follows:

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

my $strp = DateTime::Format::Strptime->new(
   pattern  => '%A%m%d_%Y',
   on_error => 'croak',
);

my $string = 'Fri0215_2013';

print $strp->parse_datetime($string)->iso8601(), "\n";

When I run this, I keep getting Fri02 is not a recognised day in this locale. I looked at the strptime docs, and it says a local is an optional attribute of strptime, and %A or %a% (tried both) should match the abbreviated day name, e.g. 'Fri',%m% should match the month number, i.e. '02' and _ obviously will match '_' (I hope!), and %Y will match the year including the century, i.e. '2013' Could anyone help?

Thanks


Solution

  • The regex that DateTime::Format::Strptime generates for %a%m%d_%Y is:

    /(\w+)([\d ]?\d)([\d ]?\d)_(\d{4})/
    

    where (\w+) is supposed to capture the weekday name. The problem is that \w matches numbers as well, so for the string Fri0215_2013 you get the following:

    weekday name: Fri02
    month: 1
    day: 5
    year: 2013
    

    The code to generate the regex for weekday names is supposed to use a list of names for your locale but falls back to \w+ because of a bug. I submitted a bug report so hopefully this gets fixed soon. [Update: It has been fixed in 1.55]


    Workaround:

    $string = s/^(...)(..)(..)_(....)/$1 $2 $3 $4/s;
    

    and

    pattern => '%a %m %d %Y'