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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.