Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert duration to hours:minutes:seconds (or similar) in Rails 3 or Ruby

Summing up:

assuming that total_seconds = 3600

Option 1:

distance_of_time_in_words(total_seconds) #=> "about 1 hour"

Option 2:

Time.at(total_seconds).utc.strftime("%H:%M:%S") #=> "01:00:00"

Note: it overflows, eg. for total_seconds = 25.hours.to_i it'll return "01:00:00" also

Option 3:

seconds = total_seconds % 60
minutes = (total_seconds / 60) % 60
hours = total_seconds / (60 * 60)

format("%02d:%02d:%02d", hours, minutes, seconds) #=> "01:00:00"

Option 4:

ActiveSupport::Duration.build(total_seconds).inspect #=> "1 hour"

# OR

parts = ActiveSupport::Duration.build(total_seconds).parts
"%02d:%02d:%02d" % [parts.fetch(:hours, 0),
                    parts.fetch(:minutes, 0),
                    parts.fetch(:seconds, 0)] #=> "01:00:00"

See: http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html

distance_of_time_in_words(3600)
 => "about 1 hour"

Ruby's string % operator is too unappreciated and oft forgotten.

"%02d:%02d:%02d:%02d" % [t/86400, t/3600%24, t/60%60, t%60]

Given t is a duration in seconds, this emits a zero-padded colon-separated string including days. Example:

t = 123456
"%02d:%02d:%02d:%02d" % [t/86400, t/3600%24, t/60%60, t%60]
=> "01:10:17:36"

Lovely.


I guess you could do also something like:

(Time.mktime(0)+3600).strftime("%H:%M:%S")

To format it as you wish.

BTW, originally I thought of using Time.at() but seems that EPOCH time on my Ubuntu is Thu Jan 01 01:00:00 +0100 1970 and not 00:00:00 hours as I expected, and therefore if I do:

Time.at(3600).strftime("%H:%M:%S")

Gives me 1 hour more than wanted.


I use this to show time durations in my Rails Project:

  1. Add a custom method to the Integer class. You can create a new file called pretty_duration.rb in the initializers folder:

    class Integer
        def pretty_duration
            parse_string = 
                if self < 3600
                    '%M:%S'
                else
                    '%H:%M:%S'
                end
    
            Time.at(self).utc.strftime(parse_string)
        end
    end
    
  2. Call seconds.pretty_duration anywhere in your project:

    275.pretty_duration     # => "04:35"
    9823.pretty_duration    # => "02:43:43"
    

This answer builds up on Lev Lukomsky's Code