in reply to Compare two dates

It's been pointed out that the date format you're using will sort by string value just fine. That means you can use the stringwise ge operator:

use strict; use warnings; my $d1 = '2019-08-01'; my $d2 = '2019-06-08'; print "\n$d2 is ", ($d2 ge $d1 ? 'greater than or equal to' : 'less than'), " $d1\n";

Perl also ships with the module Time::Piece which overloads numeric comparison operators. Therefore you could handle a broader variety of date formats, and also achieve basic date validation using the strptime method it provides:

use strict; use warnings; use Time::Piece; my ($d1, $d2) = ('2019-08-01', '2019-06-08'); my ($tp1, $tp2) = map {Time::Piece->strptime($_, '%F')} ($d1, $d2); print "\n$d2 is ", ($tp2 >= $tp1 ? 'greater than or equal to' : 'less than'), " $d1\n";

I know that DateTime was recommended. And that recommendation is fine, but what you're doing is quite simple, and doesn't really need the handling of the 800 pound gorilla. Time::Piece has been bundled with Perl since 5.10 (well, 5.9.5 if you count development releases), so it's been part of the core Perl distribution since December 2007. DateTime pulls in about 110 modules, some from the Perl core, but most from CPAN. It's a fantastic module. There's probably no better date handling module for Perl. But it's big, and you have a little problem.


Dave

Replies are listed 'Best First'.
Re^2: Compare two dates
by haukex (Archbishop) on Jul 25, 2019 at 19:56 UTC
    Perl also ships with the module Time::Piece which overloads numeric comparison operators. Therefore you could handle a broader variety of date formats, and also achieve basic date validation using the strptime method it provides

    I just wanted to second this, and the use of modules in general. Of course, everyone in this thread who pointed out that YYYY-MM-DD works with string comparisons (iff the format is exactly the same for both strings, and this is validated beforehand) is correct, and for simply determining lt/eq/gt, it'll work fine. But in my experience, one date/time task is usually followed closely by another. Next thing you know, your requirements will change, and someone will ask you to check if a date is within a certain number of days of another date. And then you'll need a module anyway.

    One advantage that DateTime has over Time::Piece is that it handles time zones, which may become important if you need to handle times as well - as long as it's just dates, Time::Piece should be just fine.