Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 847
Juan A. Navarro Avatar asked Sep 20 '11 14:09

Juan A. Navarro


People also ask

How to convert a string into date in perl?

use DateTime::Format::Strptime qw( ); my $format = DateTime::Format::Strptime->new( pattern => '%Y%m%d', time_zone => 'local', on_error => 'croak', ); my $dt = $format->parse_datetime('20111121');

How do I use Strptime in Perl?

use Time::Strptime::Format; my $format = Time::Strptime::Format->new( '%Y-%m-%d %H:%M:%S' , { time_zone => 'Asia/Tokyo' }); my ( $epoch , $offset ) = $format ->parse( '2014-01-01 00:00:00' );

How do I format a date in Perl?

say $datetime->month; say $datetime->day; say $datetime->strftime( '%Y-%m-%d-%H-%M-%S' );

How do I compare two dates in Perl?

If the dates are ISO-8601 (ie, YYYY-MM-DD) and you do not need to validate them, you can compare lexicographically (ie, the lt and gt operators.) If you need to validate the dates, manipulate the dates, or parse non standard formats -- use a CPAN module.


1 Answers

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.

like image 94
Dave Cross Avatar answered Sep 28 '22 05:09

Dave Cross