Reputation: 87
My total seconds is 125557
when i tried to convert the seconds into "H:M:S" by using
Time.at(125557).utc.strftime("%H:%M:%S")
it gives like 10:52:37
but i want actually like 34:52:37
(adding one day to 10:52:37 )
Upvotes: 2
Views: 5588
Reputation: 3152
Since Rails 6.1.0 you can do:
1.day.in_hours # => 24.0
3600.seconds.in_hours # => 1.0
Documentation: https://api.rubyonrails.org/classes/ActiveSupport/Duration.html#method-i-in_hours
Upvotes: 2
Reputation: 1483
I posted my answer here https://stackoverflow.com/a/62562658/2970582
ActiveSupport::Duration
+ inspect
gives you valid results
Upvotes: 2
Reputation: 906
You could try the ruby-duration gem if you want to deal with weeks, days, hours, minutes, and seconds more easily.
d = Duration.new(125557)
=> #<Duration:0x007f84180758e8 @days=1, @hours=10, @minutes=52, @negative=false, @seconds=37, @total=125557, @weeks=0>
d.total_hours
=> 34
d.total_minutes
=> 2092
Upvotes: 2
Reputation:
Try this
total_seconds = 125557
seconds = total_seconds % 60
minutes = (total_seconds / 60) % 60
hours = total_seconds / (60 * 60)
format("%02d:%02d:%02d", hours, minutes, seconds)
Upvotes: 3
Reputation: 230551
Well, given that 34:52:37
is not a valid time string, it makes little sense to use time parsing/conversion libraries for this. Better to calculate it manually. div
and mod
are your best friends here. Take a look:
secs = 125557
secs_in_an_hour = 3600
hours, secs = secs.divmod(secs_in_an_hour)
hours # => 34
secs # => 3157 # This now contains only minutes and seconds, no full hours
It should be quite easy to evolve this to a full working solution.
Upvotes: 8