Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to compare dates in Perl?

Tags:

perl

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.

like image 366
user855 Avatar asked Nov 16 '10 22:11

user855


People also ask

How do I compare two dates in Perl?

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.

Can you compare dates as strings?

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.


2 Answers

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.

like image 123
dawg Avatar answered Sep 27 '22 20:09

dawg


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:

  • http://datetime.perl.org/wiki/datetime/page/FAQ

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);
like image 22
Eric Strom Avatar answered Sep 27 '22 21:09

Eric Strom