Numeric to time/period format (Ex: 1.to_s(:time, format: '%H:%M:%S'))

Hello Rails Community!

Every time that I need to calculate a period of time and need to display it in a custom format I use a converter that works like this code below.

31104002.to_s(:time, format: ‘%y-%m-%d %H:%M:%S’)

‘01-00-00 00:00:02’

3602.to_s(:time, format: ‘%d %H:%M:%S’)

‘01 00:00:02’

3602.to_s(:time, format: ‘%d days, %H hours, %M minutes and %S seconds’)

‘01 days, 00 hours, 00 minutes and 02 seconds’

Is it helpful? Interesting?

You can currently do that using a (probably not easy to find name) #strftime.

I don’t think there’s a need to clone that method and make it as part of #to_s though.


Hi Prem, thanks for you reply :slight_smile:

strftime is a Time method, not Numeric. The diff between dates results a Float. If you ask this result if is_a?(Numeric) returns true, is_a?(Time) returns false.

My proposal is a helper like “strfperiod” if it is in Ruby. Working with diff time periods, not dates.


I create a gem to do the example: