14

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.

Mark Canlas
  • 9,385
  • 5
  • 41
  • 63
user855
  • 19,048
  • 38
  • 98
  • 162
  • You might be interested in this [stack-exchange proposal](http://area51.stackexchange.com/proposals/11464/code-review?referrer=aWNm_PdciyFqjFW8CUacGw2 "code review"). It's almost ready to begin beta, just needs a few more. – greatwolf Jan 19 '11 at 04:55

3 Answers3

36

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.

szabgab
  • 6,202
  • 11
  • 50
  • 64
dawg
  • 98,345
  • 23
  • 131
  • 206
23

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);
Marco
  • 8,958
  • 1
  • 36
  • 56
Eric Strom
  • 39,821
  • 2
  • 80
  • 152
  • 19
    One of the many nice things about DateTime is it has full operator overloading -- e.g. you can compare two DateTime objects as `if ($dt1 < $dt2) { ... }` – Ether Nov 16 '10 at 22:14
3

Date::Manip is a very good module for that.

szabgab
  • 6,202
  • 11
  • 50
  • 64
Baramin
  • 1,359
  • 10
  • 12