If you've already got DateTime objects, then you should use their methods to do all your date/time math, and not be working with regexes or manual date/time math. To turn a string into a DateTime object, I like DateTime::Format::Strptime. Note that you need to supply the correct time zone to DateTime::Format::Strptime for the comparison to work, and also that subtract_datetime_absolute is "the only way to accurately measure the absolute amount of time between two datetimes, since units larger than a second do not represent a fixed number of seconds." (Although in this case that level of accuracy might not be needed, and regular DateTime::Duration calculations might be enough.)

use warnings; use strict; use DateTime::Format::Strptime; my $now = DateTime->now; print "$now\n"; my $strp = DateTime::Format::Strptime->new(on_error=>'croak', pattern => '%Y-%m-%d %H:%M:%S', time_zone=>'UTC'); my $dtevent = $strp->parse_datetime('2017-06-28 05:30:31'); print "$dtevent\n"; my $diff_sec = $now->subtract_datetime_absolute($dtevent) ->in_units('seconds'); my $diff_hours = $diff_sec/(60*60); print "$diff_sec s / $diff_hours h\n"; if ($diff_hours>2) { print "$dtevent was more than 2 hours ago\n"; }

In reply to Re: execute if date is greater then 2hours by haukex
in thread execute if date is greater then 2hours by snehit.ar

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.