perlparsingdatetime

How to parse a string into a DateTime object in Perl?


I know about the DateTime Perl module, and many of the DateTime::Format:: modules to parse specific kinds of date/time formats. However given some examples of date/time strings, how can I figure out (at coding/design time, not at runtime) which specific module should I use?

For example, I want to parse strings like: October 28, 2011 9:00 PM PDT

Is there a list somewhere of the most common date/time formats where I could look this up and find which would be the most suitable module?

I also know about some modules which try to "guess" the format for each given string at runtime and do their best. But, for sensitive applications, I would like to determine (as strictly as possible) the format first when designing an application, and then use a module which will warn me if a string does not match the specified format.

How should I go about this?


Solution

  • DateTime::Format::Strptime takes date/time strings and parses them into DateTime objects.

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use DateTime::Format::Strptime;
    
    my $parser = DateTime::Format::Strptime->new(
      pattern => '%B %d, %Y %I:%M %p %Z',
      on_error => 'croak',
    );
    
    my $dt = $parser->parse_datetime('October 28, 2011 9:00 PM PDT');
    
    print "$dt\n";
    

    The character sequences used in the pattern are POSIX standard. See 'man strftime' for details.