Tuesday, May 27, 2008

Ruby: Format seconds into minutes to_minutes function

I created this function to turn seconds into minutes.
Example: 500 seconds should be displayed as 8:00 minutes.




def to_minutes(seconds)

m = (seconds/60).floor
s = (seconds - (m * 60)).round

# add leading zero to one-digit minute
if m < 10
m = "0#{m}"
end
# add leading zero to one-digit second
if s < 10
s = "0#{s}"
end
# return formatted time
return "#{m}:#{s}"
end


8 comments:

  1. This was just what I was looking for. Thanks!

    ReplyDelete
  2. 500 Seconds are 8 minutes but never mind. :-)

    ReplyDelete
  3. Perfect! Thanks for posting this up, it's a handy tidbit to have around and saved me having to dream it up myself.

    ReplyDelete
  4. If I may make a suggestion...

    def to_minutes(seconds)

    m = (seconds/60).floor
    s = (seconds - (m * 60)).round

    # return formatted time
    return "%02d:%02d" % [ m, s ]
    end

    ReplyDelete
  5. awesome! exactly what I was looking for! Thank you.

    I made a slight change to it for myself (excuse if poorly coded as newbie)

    def to_minutes(seconds)
    h = (seconds/60/60).floor
    m = (seconds/60).floor
    m = m - (h * 60) if h
    s = (seconds - (m * 60)).round
    # return formatted time
    p "%02d:%02d:%02d" % [ h, m, s ]
    end
    to_minutes(12001)

    ReplyDelete
  6. Correction to my previous comment;

    def to_minutes(seconds)
    h = (seconds/60/60).floor
    m = (seconds/60).floor
    s = (seconds - (m * 60)).round
    m = m - (h * 60) if h
    # return formatted time
    p "%02d:%02d:%02d" % [ h, m, s ]
    end
    to_minutes(12001)

    ReplyDelete