开发者

What is the best way to compare dates in 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.


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:

  • 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);


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜