tomazos has asked for the wisdom of the Perl Monks concerning the following question:

Given a timestamp in the form '20050802033259' I want a function that gives an approximate relative time from now (as according to the system clock).

sub timediff($;$) { my $then = $_[0]; my $now; if (defined $_[1]) { $now = $_[1]; } else { # set $now from system clock } my $diff; # $diff = relative time between $now and $then return $diff; }

$diff should be something like '30 seconds ago', '4 years from now', 'last month', '4 hours from now', 'yesterday', '2 days ago', etc.

Is there a CPAN module out there that does it?


Solved: Ahhh CPAN. You've got to love it...

sub timediff($) { use Time::Piece; use Time::Piece::MySQL; use Time::Duration; my $time = Time::Piece->from_mysql_timestamp( $_[0] ); my $now = localtime; my $diff = ago ($now->epoch() - $time->epoch(), 1); return $diff; }

Any improvements on the above would be greatly appreciated.

-Andrew.


Andrew Tomazos  |  andrew@tomazos.com  |  www.tomazos.com

Replies are listed 'Best First'.
Re: Descriptive Relative Time
by Limbic~Region (Chancellor) on Aug 02, 2005 at 14:46 UTC

      Time::Duration is probably the right one. It converts seconds into an English equivalent (e.g. "20 days, 4 hours, 13 minutes, and 25 seconds ago") with support for truncating to an approximation (e.g. "20 days, 4 hours ago").

      -xdg

      Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

        xdg,
        As does my RFC: Seconds2English. It won't however give you a response like 'yesterday' and 'last month'. That is why I said any solution is likely going to need to be tweaked for the specific responses.

        Cheers - L~R

Re: Descriptive Relative Time
by kwaping (Priest) on Aug 02, 2005 at 14:43 UTC
    Check out Date::Calc for date calculations. I don't think it will go any more granular than days though.

    Update
    I notice that your date/time format is easily parseable. One thing you can do is use Date::Calc's Date_to_Time() function to convert that information into a system time format (aka seconds-since-epoch).
    $time = Date_to_Time($year,$month,$day, $hour,$min,$sec);
    You could then operate on that system time in a number of ways, including manual subtraction to find the difference in seconds. You should be able to see where to go from there. :)
Re: Descriptive Relative Time
by blazar (Canon) on Aug 02, 2005 at 14:46 UTC