开发者

How can I get approximate time passed since some timestamp?

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/hou开发者_如何转开发rs/minutes/seconds between two dates, to use in sentence like "N days ago" or "M months ago"


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.


Well, not very difficult to write your own.

Calculate relative time in C#


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.


You might take a look at the Time::Ago module on CPAN (I'm the author). It's a Perl port of the time_ago_in_words() helper from Rails.

Given a duration, it returns a readable string approximation. From the Rails docs:

0  29 secs
  less than a minute

30 secs  1 min, 29 secs
  1 minute

1 min, 30 secs  44 mins, 29 secs
  [2..44] minutes

44 mins, 30 secs  89 mins, 29 secs
  about 1 hour

89 mins, 30 secs  23 hrs, 59 mins, 29 secs
  about [2..24] hours

23 hrs, 59 mins, 30 secs  41 hrs, 59 mins, 29 secs
  1 day

41 hrs, 59 mins, 30 secs  29 days, 23 hrs, 59 mins, 29 secs
  [2..29] days

29 days, 23 hrs, 59 mins, 30 secs  44 days, 23 hrs, 59 mins, 29 secs
  about 1 month

44 days, 23 hrs, 59 mins, 30 secs  59 days, 23 hrs, 59 mins, 29 secs
  about 2 months

59 days, 23 hrs, 59 mins, 30 secs  1 yr minus 1 sec
  [2..12] months

1 yr  1 yr, 3 months
  about 1 year

1 yr, 3 months  1 yr, 9 months
  over 1 year

1 yr, 9 months  2 yr minus 1 sec
  almost 2 years

2 yrs  max time or date
  (same rules as 1 yr)

CPAN module

Repository


[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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜