I am using Rails 4, Ruby 2.1 with PostgreSQL.
I have a database field called duration
which is an interval data type.
When pulling out the data in this column it returns in the format of hh:mm:ss
, e.g. 01:30:00
.
I am trying to figure out a way to display this as 1 hour, 30 minutes
.
Other examples:
02:00:00
to 2 hours
02:15:00
to 2 hours, 15 minutes
02:01:00
to 2 hours, 1 minute
Just use duration
+ inspect
seconds = 86400 + 3600 + 15
ActiveSupport::Duration.build(seconds).inspect
=> "1 day, 1 hour, and 15.0 seconds"
Or a it can be a little be customized
ActiveSupport::Duration.build(seconds).parts.map do |key, value|
[value.to_i, key].join
end.join(' ')
=> "1days 1hours 15seconds"
P.S.
You can get seconds with
1.day.to_i
=> 86400
Time can be parsed only in ISO8601 format
ActiveSupport::Duration.parse("PT2H15M").inspect
=> "2 hours and 15 minutes"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With