I need to convert the following strings to DateTime objects so I can compare them:
2016-06-30T09:00:00-04:00
2016-07-01T15:37:25
Both objects should use the EST timezone. How can I do this?
I need to convert the following strings to DateTime objects so I can compare them:
2016-06-30T09:00:00-04:00
2016-07-01T15:37:25
Both objects should use the EST timezone. How can I do this?
First of all, EST
is used to refer to a multitude of different time zone offsets. Presumably, you meant UTC-05:00
.
Second of all, if one is to perform datetime arithmetic, one rarely wants to deal with offsets; one almost always wants time zones associated with a geographical location (such as America/New_York
). America/New_York
would be a suitable choice for use below, but I used the more flexible local
instead.
use strict;
use warnings;
use feature qw( say );
use DateTime::Format::Strptime qw( );
my $format1 = DateTime::Format::Strptime->new(
pattern => "%Y-%m-%dT%H:%M:%S%Z",
on_error => "croak",
);
my $format2 = DateTime::Format::Strptime->new(
pattern => "%Y-%m-%dT%H:%M:%S",
time_zone => "local",
on_error => "croak",
);
my $dt1 = $format1->parse_datetime('2016-06-30T09:00:00-04:00');
my $dt2 = $format2->parse_datetime('2016-07-01T15:37:25');
Then, you can do whatever you want. You mentioned you wanted to compare them, which can be done using numerical comparison operators (e.g. $dt1 < $dt2
).
The following example converts the timestamps into RFC3339 timestamps (the timestamp format used by internet standards):
$dt1->set_time_zone("UTC");
say "dt1: " . $dt1->strftime("%Y-%m-%dT%H:%M:%SZ");
$dt2->set_time_zone("UTC");
say "dt2: " . $dt2->strftime("%Y-%m-%dT%H:%M:%SZ");