Personally, I like DateTime (usually together with DateTime::Format::Strptime for parsing).

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

In reply to Re: choosing closest date to a given date by haukex
in thread choosing closest date to a given date by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.