Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: execute if date is greater then 2hours

by haukex (Archbishop)
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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1193769]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2022-08-11 05:58 GMT
Find Nodes?
    Voting Booth?

    No recent polls found