Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: execute if date is greater then 2hours

by haukex (Monsignor)
on Jun 28, 2017 at 08:01 UTC ( #1193769=note: print w/replies, xml ) Need Help??

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 (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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1193769]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2017-10-22 16:20 GMT
Find Nodes?
    Voting Booth?
    My fridge is mostly full of:

    Results (273 votes). Check out past polls.