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

后端 未结 13 751
一整个雨季
一整个雨季 2021-01-29 23:52

I have a feeling there is a simple/built-in way to do this but I can\'t find it.

I have a duration (in seconds) in an integer and I want to display it in a friendly form

13条回答
  •  伪装坚强ぢ
    2021-01-30 00:35

    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"
    

    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"
    

    use Option1 if you want words, Option2 if you want H:M:S format, Option3 if you want H:M:S format and there can be more than 24 hours

提交回复
热议问题