Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Simple (I thought) time comparison?

by haukex (Archbishop)
on Dec 20, 2016 at 14:08 UTC ( [id://1178209]=note: print w/replies, xml ) Need Help??


in reply to Simple (I thought) time comparison?

Hi sjessie,

As hippo and davido have already identified, the issue is with time zones. Personally, I like to use the DateTime module since it includes a lot of functionality, including time zones. (Because of that it's a little more heavyweight, but that should only be noticeable if your script does a lot of date/time calculations, so personally I just throw all of my date/time stuff at the DateTime suite because it can handle it all, and only consider using other modules as an optimization if necessary.)

Anyway, here are two methods that work. Note that this handles time zones properly, for example try changing the first "America/New_York" to "America/Chicago". Update: Just to emphasize this, the key is that all the DateTime objects involved in the calculations and comparisons need to have their time zones set properly.

use warnings; use strict; use DateTime; use DateTime::Format::Strptime; my $old_str = 'Dec 19 17:01:00 2016'; # normally, $now = DateTime->now my $now = DateTime->new(year=>2016,month=>12,day=>19, hour=>17,minute=>7,second=>6,time_zone=>'America/New_York'); print "now=", $now->strftime('%Y-%m-%d-%H-%M-%S %Z'), "\n"; my $strp = DateTime::Format::Strptime->new( on_error=>'croak', pattern => '%b %d %T %Y', time_zone=>'America/New_York' ); my $old = $strp->parse_datetime($old_str); print "old=", $old->strftime('%Y-%m-%d-%H-%M-%S %Z'), "\n"; # approach one: difference my $diff_sec = $now->subtract_datetime_absolute($old) ->in_units('seconds'); print "diff_sec: $diff_sec (", sprintf("%.1f",$diff_sec/60), " minutes)\n"; # approach two: compare to another DateTime my $halfago = $now->clone->subtract(minutes=>30); print "halfago=", $halfago->strftime('%Y-%m-%d-%H-%M-%S %Z'), "\n"; # note comparators are overloaded for DateTime objects print "halfago ", ($halfago>$old?'>':'<='), " old\n";

Hope this helps,
-- Hauke D

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1178209]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (2)
As of 2024-04-19 21:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found