I need to read 2 dates and compare them.
One date is the current_date (year,month,date) the other is determined by the business logic. I then need to compare the 2 dates and see if one is before the other.
How can I do the same in Perl?
I am searching for good documentation, but I am finding so many Date modules in Perl. Don't know which one is appropriate for it.
Re: How to compare two dates? DateTime has a ->compare( $dt1, $dt2 ) method that returns -1 if $dt1 < $dt2, 0 if $dt1 == $dt2, 1 if $dt1 > $dt2. DateTime objects also overload the comparison operators (< > == etc.). To parse a string into a DateTime object, take a look at DateTime::Format::Strptime.
You can't compare just any date string. For instance, "13-Dec-2020" < "20-Apr-2020" alphabetically but not conceptually. But ISO date strings are neatly comparable, for instance, "2020-12-13" > "2020-04-20" both conceptually and alphabetically.
If the dates are ISO-8601 (ie, YYYY-MM-DD) and you do not need to validate them, you can compare lexicographically (ie, the lt
and gt
operators.)
If you need to validate the dates, manipulate the dates, or parse non standard formats -- use a CPAN module. The best, IMHO, are DateTime and DateCalc. Date-Simple is pretty good too.
A good place to start on your own journey is to read The Many Dates of Perl and the DateTime site.
One of the most popular date modules is DateTime which will handle all of the corner cases and other issues surrounding date math.
This link is a FAQ for DateTime which may help you get started:
The way the DateTime
module works is that you convert your dates (which will presumably be strings) into DateTime
objects, which you can then compare using one of several DateTime
methods.
In the examples below, $dt1
and $dt2
are DateTime
objects.
$days
is the delta between the two dates:
my $days = $dt1->delta_days($dt2)->delta_days;
$cmp
is -1, 0 or 1, depending on whether $dt1
is less than, equal to, or more than $dt2
.
my $cmp = DateTime->compare($dt1, $dt2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With