use warnings;
use strict;
use DateTime;
use DateTime::Format::Strptime;
my @time_strs = qw/
2018-09-14T14:35:56Z 2018-09-13T09:32:12Z 2018-09-12T20:12:16Z
2018-08-07T07:12:45Z 2018-08-01T23:55:59Z 2018-07-24T15:39:01Z
2018-01-04T18:19:20Z 2017-11-03T10:26:49Z 2017-07-17T17:22:04Z/;
my @target_strs = qw/
2018-09-13T23:55:00Z 2018-09-14T00:55:00Z
2018-04-14T09:33:12Z 2018-04-15T09:33:12Z/;
for my $target_str (@target_strs) {
my $strp = DateTime::Format::Strptime->new( on_error=>'croak',
pattern => '%Y-%m-%dT%H:%M:%SZ', time_zone=>'UTC' );
my $target_dt = $strp->parse_datetime($target_str);
my @dts;
for my $t (@time_strs) {
my $dt = $strp->parse_datetime($t);
my $diff_s = $dt->subtract_datetime_absolute($target_dt)
->in_units('seconds');
push @dts, { dt=>$dt,
diff_s=>$diff_s, absdiff_s=>abs($diff_s) };
}
@dts = sort { $a->{absdiff_s} <=> $b->{absdiff_s} } @dts;
my $closest = $dts[0];
print "Closest is ",
$closest->{dt}->strftime('%Y-%m-%dT%H:%M:%S %Z'),
", which is ", $closest->{diff_s}>0 ? 'after ' : 'before ',
$target_dt->strftime('%Y-%m-%dT%H:%M:%S %Z'), "\n";
}
__END__
Closest is 2018-09-13T09:32:12 UTC, which is before 2018-09-13T23:55:0
+0 UTC
Closest is 2018-09-14T14:35:56 UTC, which is after 2018-09-14T00:55:0
+0 UTC
Closest is 2018-01-04T18:19:20 UTC, which is before 2018-04-14T09:33:1
+2 UTC
Closest is 2018-07-24T15:39:01 UTC, which is after 2018-04-15T09:33:1
+2 UTC
|