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

后端 未结 13 753
一整个雨季
一整个雨季 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:42

    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.

    0 讨论(0)
提交回复
热议问题