Time Difference To String

pradeep's Avatar author of Time Difference To String
This is an article on Time Difference To String in Perl.
Rated 5.00 By 1 users
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.

Code: Perl
sub time2string
{
    $seconds = shift;
    # Convert seconds to days, hours, minutes, seconds
    @parts = gmtime($seconds);
    $ret = '';
    if(sprintf("%4d",@parts[7])>0)
    {
        $ret .= sprintf("%4d",@parts[7]);
        $ret .= sprintf(" %s",(@parts[7]>1)?'days':'day');
    }
    if(sprintf("%4d",@parts[2])>0)
    {
        $ret .= sprintf("%4d",@parts[2]);
        $ret .= sprintf(" %s",(@parts[2]>1)?'hours':'hour');
    }
    if(sprintf("%4d",@parts[1])>0)
    {
        $ret .= sprintf("%4d",@parts[1]);
        $ret .= sprintf(" %s",(@parts[1]>1)?'minutes':'minute');
    }
    if(sprintf("%4d",@parts[0])>0)
    {
        $ret .= sprintf("%4d",@parts[0]);
        $ret .= sprintf(" %s",(@parts[0]>1)?'seconds':'second');
    }

    return $ret;
}

Example Usage:
Code: Perl
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!