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

Hi everyone
I'll be really happy if someone can help med figure out how to compare to dates when the date-format is 'YYYY-MM-DD'
Thanks

Replies are listed 'Best First'.
Re: date comparison
by Tanalis (Curate) on May 20, 2003 at 13:20 UTC
    The way I always do this is either to use the lt and gt operators on the YYYY-MM-DD string (they'll compare each digit in turn, and the hyphens will be compared simply with each other, so they won't affect the comparison), or to substitute out the hyphens, and then use normal numeric comparison. A couple examples of this are as follows:
    my $date1 = "2003-05-20"; my $date2 = "2003-04-19"; if ($date1 gt $date2) { print "Date 1 is bigger" } # # # alternatively my $date1 = "2003-05-20"; my $date2 = "2003-04-19"; $date1 =~ s/\-//g; $date2 =~ s/\-//g; if ($date1 > $date2) { print "Date 1 is bigger" }
    Hope that helps.

    -- Foxcub
    #include www.liquidfusion.org.uk

Re: date comparison
by Joost (Canon) on May 20, 2003 at 13:37 UTC
    The above suggestions are correct for just sorting dates, but if you need to know the difference between dates you need to use another approach:

    Lowlevel approach:

    You can use POSIX's strftime() function Time::Local's timelocal() function to convert dates to epoch seconds, and substract them, but if you need to convert the difference in seconds back to anything more complicated than 24 hour days, you probably need something more high-level.

    use CPAN

    You can also take a look at the (literally) hundreds of CPAN date modules. One you can probably use is Date::Calc.

    Joost

    update: finally found the right standard module to convert back from localtime.

    -- #!/usr/bin/perl -np BEGIN{@ARGV=$0}s(^([^=].*)|=)()s; =Just another perl hacker\
Re: date comparison
by fglock (Vicar) on May 20, 2003 at 14:46 UTC
Re: date comparison
by arthas (Hermit) on May 20, 2003 at 14:01 UTC
    You can use Date::Manip to obtain the delta between one date and the other. Here's an example:
    use Date::Manip; $date1=&ParseDate('2004-10-28'); $date2=&ParseDate('2003-10-23'); $delta=&DateCalc($date1,$date2,\$err,1); print $delta."\n";
    The content of $delta is a string which you have to know how to read. The format is:
    YY:MM:WK:DD:HH:MM:SS (the years, months, etc. between the two)
    Actually, there are several options for date comaprison. Read perldoc Date::Manip for more information.

    Michele.
      From the rumors I've heard, Date::Manip is considered to be slow and heavy. You might gain something by splitting the date into year, month, and date and feeding it to Date_to_Time sub from the Date::Calc module. Works like a charm too, you know. :)

      Leonid Mamtchenkov aka TVSET

Re: date comparison
by Thelonius (Priest) on May 20, 2003 at 13:18 UTC
    gt, ge, lt, le, ne, eq, cmp