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 |