http://qs321.pair.com?node_id=1193769


in reply to execute if date is greater then 2hours

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"; }

Replies are listed 'Best First'.
Re^2: execute if date is greater then 2hours
by snehit.ar (Beadle) on Jun 28, 2017 at 10:41 UTC
    Thank you. @haukex , not only share the solution but also explain well about the cause . Appreciate you help.