lmojzis
lmojzis

Reputation: 561

Converting hours, minutes and seconds to seconds in ruby

I was wondering how to safely convert HH:MM:SS to seconds in ruby, given the input will only be in HH:MM:SS (or H:M:S), without days.

Days would have to be in hours already - "168:00:00" instead of "7 days, 00:00:00".

Upvotes: 2

Views: 4945

Answers (3)

xlynx
xlynx

Reputation: 167

'12:34:56'.split(':').map(&:to_i).inject(0) { |a, b| a * 60 + b }
=> 45296

Upvotes: 13

sawa
sawa

Reputation: 168071

h, m, s = "168:00:00".split(":").map(&:to_i)
h %= 24
(((h * 60) + m) * 60) + s

Upvotes: 3

lmojzis
lmojzis

Reputation: 561

The solution is quite simple:

secs = 0
=> 0
"12:34:56".split(":").reverse.each_with_index do |x,y|
  "#{secs} += (#{x.to_i})*(#{60**y})"
  secs += (x.to_i)*(60**y)
end
=> ["56", "34", "12"]
secs
=> 45296

No use of Time or DateTime and no timezone problems!

Cheers!

Upvotes: -3

Related Questions