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?
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');
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' );
say $datetime->month; say $datetime->day; say $datetime->strftime( '%Y-%m-%d-%H-%M-%S' );
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With