views:

65

answers:

4

Is there any useful module on CPAN that returns number of biggest fractions of date interval, i.e. return integer number of years/months/days/hours/minutes/seconds between two dates, to use in sentence like "N days ago" or "M months ago"

+1  A: 

Time::Duration seems to be a natural choice for what you try to accomplish. I haven't tried it though. Only caveat seems to be that it already gives you phrases like "M months ago", so you might need to parse its output for non-English output.

honk
+2  A: 

Well, not very difficult to write your own.

http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time

codeholic
That's a venerable question to be cross-referencing!
Jonathan Leffler
+4  A: 

DateTime and DateTime::Duration are the best modules:

use strict;
use warnings;

use DateTime;
use DateTime::Duration;
use Data::Dumper;

my $dt1 = DateTime->now;
my $dt2 = DateTime->new(
    year => 2001,
    month => 01,
    day => 01
);

my $duration = $dt1 - $dt2;
print Dumper($duration);

produces:

$VAR1 = bless( {
                 'seconds' => 38,
                 'minutes' => 181,
                 'end_of_month' => 'wrap',
                 'nanoseconds' => 0,
                 'days' => 20,
                 'months' => 110
               }, 'DateTime::Duration' );

You can format absolute times and durations using the sister modules DateTime::Format and DateTime::Format::Duration.

Ether
codeholic
A: 

[This isn't really an answer, but I think it's relevant.]

If you're going to get into date/time manipulation and calculation, you're best off keeping to the DateTime family of modules. Not only do they have the best handling of timezones that I've found, but they all work with each other. I've never had a problem in this domain which I couldn't find a module in DateTime to solve it.

Thomas Erskine