1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Time Difference To String

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

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    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:
    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:
    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