in reply to How to compare two dates?

There are a lot of methods. The method suggested by "anonymous monk" is ok. Recently I used this way, with "Time::Piece".
#format first date (get by localtime(time) ) my $date_1 = Time::Piece ->strptime($date, "%Y%m%d%H%M"); #format second date (get by localtime(time) ) my $date_2 = Time::Piece ->strptime($date2", "%Y%m%d%H%M"); #get the diff in seconds my $diff = $date_1 - $date_2;

Replies are listed 'Best First'.
Re^2: How to compare two dates?
by Anonymous Monk on Sep 18, 2014 at 10:24 UTC

    you can make use of CPAN module Date::Calc to perform all the date related functions

Re^2: How to compare two dates?
by Anonymous Monk on Aug 03, 2019 at 22:57 UTC
    Hi, I am getting error while using the above code snippet. for $date i am using localtime and it is giving me parsing error.

      Hi, so when you got the error, did you print out the value of $date to see what you were passing to the parser?

      The first answer you got had all the tools you needed. Here I've added Test::More so I can set up some simple testing of my subroutine, checking comparisons that I already know the answer to. It's a good way to develop your code.

      use strict; use warnings; use feature 'state'; use Test::More; use DateTime::Format::Strptime; for my $line (<DATA>) { chomp $line; my ( $first, $second, $expected ) = split /,/, $line; is( date_cmp($first, $second), $expected, "compared to $first, $se +cond is $expected" ); } done_testing; exit; sub date_cmp { state $parser = DateTime::Format::Strptime->new(pattern => '%m/%d/ +%Y'); my $dt1 = $parser->parse_datetime(shift) or die $parser->errmsg; my $dt2 = $parser->parse_datetime(shift) or return 'invalid'; return 'equal' if $dt1 eq $dt2; return $dt1 > $dt2 ? 'earlier' : 'later'; } __DATA__ 03/02/1999,03/01/1999,earlier 03/02/1999,03/03/1999,later 03/02/1999,03/02/1998,earlier 03/02/1999,03/02/2000,later 03/02/1999,03/02/1999,equal 03/02/1999,03/02/199 ,invalid
      Output:
      $ perl dt.pl ok 1 - compared to 03/02/1999, 03/01/1999 is earlier ok 2 - compared to 03/02/1999, 03/03/1999 is later ok 3 - compared to 03/02/1999, 03/02/1998 is earlier ok 4 - compared to 03/02/1999, 03/02/2000 is later ok 5 - compared to 03/02/1999, 03/02/1999 is equal ok 6 - compared to 03/02/1999, 03/02/199 is invalid 1..6

      Hope this helps!


      The way forward always starts with a minimal test.