Search code examples
perlcomparison

Comparing two Time::Piece objects


I experimented with the Time::Piece and Time::Seconds packages and wrote the below script to compare two Time::Piece objects. What I'm trying to do is to determine if the current time of day is before or after a specific time of day. In this case I've set the specific time to be 10:30:00.

I printed out the two Time::Piece values, and from that it looks like the codes to should work, but the result is not I'm expecting.

Could anyone see what's wrong with my codes?

use strict;
use warnings;
use Time::Piece;
use Time::Seconds;

my $settDate;
my $time = Time::Piece->new;
my $eod  = Time::Piece->strptime($time->date . "T10:30:00", '%Y-%m- %dT%H:%M:%S');
print "Time is: ${time}, EOD is: ${eod}\n";
if ($time > $eod) {
    print "Yes, we've passed EOD.\n";
    $settDate = $time->strftime('%Y/%m/%d');
} else {
    print "No, we haven't passed EOD yet\n";
    $settDate = ($time - ONE_DAY)->strftime('%Y/%m/%d');
}
print "Default date is: ${settDate}\n";

Output shows:

Time is: Wed Jul  3 15:44:26 2019, EOD is: Wed Jul  3 10:30:00 2019
No, we haven't passed EOD yet
Default date is: 2019/07/02

Solution

  • The unexpected comparison result is probably due to different timezone offsets in $time and $eod - Time::Piece->new yields a local time, while the Time::Piece->strptime yields UTC.
    The simplest fix would be to always use UTC: replace Time::Piece->new with Time::Piece->gmtime.