Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Perl (http://www.go4expert.com/articles/perl-tutorials/)
-   -   Time Difference To String (http://www.go4expert.com/articles/time-difference-string-t6980/)

pradeep 23Oct2007 15:18

Time Difference To String
 
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!


All times are GMT +5.5. The time now is 12:47.