0

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?

ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110
user3784251
  • 520
  • 2
  • 10
  • 24

1 Answers1

2

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");
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • This gives a error like "I don't recognise the timezone 8. at trydate.pl line 21." when there is a value other than 00 in seconds eg: 2016-07-01T16:32:08-04:00. Why it is so? how to discard this error? – user3784251 Jul 01 '16 at 20:51
  • No, `$format1->parse_datetime('2016-07-01T16:32:08-04:00')` does not produce any error. I don't think that's what you actually passed. – ikegami Jul 01 '16 at 20:56
  • `my $format1 = DateTime::Format::Strptime->new( pattern => "%Y-%m-%dT%H:%M:%S%Z", on_error => "croak", ); my $dt1 = $format1->parse_datetime('2016-07-01T16:32:08-04:00'); $dt1->set_time_zone("EST"); print "dt1: 2016-07-01T16:32:08-04:00" . $dt1->strftime("%Y-%m-%dT%H:%M:%SZ")."\n\n";` – user3784251 Jul 01 '16 at 21:00
  • The above mentioned is the code i have ran, results in `I don't recognise the timezone 8. at trydate.pl line 21.`. But, if i change the "08" to "00" it runs and gives the output correctly! – user3784251 Jul 01 '16 at 21:01
  • It produces `dt1: 2016-07-01T16:32:08-04:002016-07-01T15:32:08Z` as it should for me. Upgrade your modules? /// Note that `$dt1->set_time_zone("EST");` is wrong, as I previously explained. Do you perhaps mean `$dt1->set_time_zone("America/New_York");` or `$dt1->set_time_zone("local");`? – ikegami Jul 01 '16 at 21:02