slugger415 has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I have a script using Time::Piece that compares dates/times to localtime. I am getting some unexpected behavior which I've tracked to a 7 hour difference in time zones (I'm on the U.S. west coast).

My snippet:

use Time::Piece; use Time::Seconds; use strict; my $dateformat = "%H:%M:%S, %m/%d/%Y"; my $date1 = "11:56:00, 09/17/2022"; my $date2 = "14:31:00, 09/16/2022"; my $date3 = "11:20:00, 09/13/2022"; my $t = localtime; print "Current time: \n", $t, $/,$/; $date1 = Time::Piece->strptime($date1, $dateformat); $date2 = Time::Piece->strptime($date2, $dateformat); $date3 = Time::Piece->strptime($date3, $dateformat); my(@ds) = ($date1,$date2,$date3); foreach my $dt (@ds){ print $dt, $/; if($dt < $t){ print " in the past...\n"; } else{ print " in the future...\n"; } }

This results in:

Current time: Fri Sep 16 07:39:44 2022 Sat Sep 17 11:56:00 2022 in the future... Fri Sep 16 14:31:00 2022 in the past... Tue Sep 13 11:20:00 2022 in the past...

As you can see the 2nd date for Fri Sep 16 should be "in the future...". If I change $t to gmtime I get the behavior I want, but I don't want to use gmtime for comparison. Is there a way to do this with localtime? Thank you.

Replies are listed 'Best First'.
Re: Time::Piece and localtime?
by choroba (Cardinal) on Sep 16, 2022 at 16:07 UTC
    If you don't supply the timezone to strptime, it uses UTC. localtime always knows its timezone, though. One of the ways how to construct the object in the current zone is to use localtime to construct the object instead of the class:
    $date1 = localtime->strptime($date1, $dateformat);

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

      that worked, thank you!

Re: Time::Piece and localtime?
by Corion (Patriarch) on Sep 16, 2022 at 15:42 UTC

    Time::Piece has no idea what timezone your parsed times are in. Maybe you can supply a time zone offset using the ->tzoffset method? Or alternatively, add the appropriate timezone to your parsed string and the format?

      how is tzoffset used? I don't see any description of that.

      Thanks.