1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Time Difference To String

Discussion in 'Perl' started by pradeep, Oct 23, 2007.

  1. pradeep

    pradeep Team Leader

    Many times we require to output the time difference between two dates/time in human readable form like '5 minutes 18 seconds'...
    Writing a whole subroutine to perform the same can be tiresome and messy, I've written a small subroutine which uses Perl's gmtime function to achieve the same.

    sub time2string
        $seconds = shift;
        # Convert seconds to days, hours, minutes, seconds
        @parts = gmtime($seconds);
        $ret = '';
            $ret .= sprintf("%4d",@parts[7]);
            $ret .= sprintf(" %s",(@parts[7]>1)?'days':'day');
            $ret .= sprintf("%4d",@parts[2]);
            $ret .= sprintf(" %s",(@parts[2]>1)?'hours':'hour');
            $ret .= sprintf("%4d",@parts[1]);
            $ret .= sprintf(" %s",(@parts[1]>1)?'minutes':'minute');
            $ret .= sprintf("%4d",@parts[0]);
            $ret .= sprintf(" %s",(@parts[0]>1)?'seconds':'second');
        return $ret;
    Example Usage:
    print time2string(60*60),"\n";
    print time2string(60*60*24),"\n";
    print time2string((60*60*24*2)+59),"\n";
    #   Output
    #   1 hour
    #   1 day
    #   2 days  59 seconds
    I hope that's helpful!

Share This Page