Reputation: 25378
Say it took someone 3 minutes and 45 seconds to complete a task.
I'd represent that as 3:45.
But what I need to do is, assuming I'm given 3:45
, convert that to the number of seconds it took.
So when given 3:45
, I want to convert that to 225
.
This would need to work with Ruby 1.8.7.
Upvotes: 0
Views: 428
Reputation: 11198
class String
def to_secs
split(':').reverse.zip([1, 60, 60*60]).inject(0) { |m, e| m += e[0].to_i * e[1] }
end
end
puts '3:45'.to_secs # 225
puts '1:03:45'.to_secs # 3825
Upvotes: 1
Reputation: 96604
def time_to_seconds(str)
time_in = []
time_in = str.split(":").reverse
asec = 0
secs = [1, 60, 60*60, 60*60*24]
time_in.size.times do {|i|
asec += secs[i].to_i * time_in[i].to_i
end
sec
end
Upvotes: 1
Reputation: 18203
I'd be careful about reinventing the wheel here. While you may assume you'll have only minutes and seconds, and that you'll always have the same format, it's safer to have something more robust.
Check out chronic_duration, a gem for parsing elapsed time.
Upvotes: 0
Reputation:
You could use something like Dave suggested, or if you need more stuff, there's a duration library that does this stuff.
It would look like:
001:0> ChronicDuration.parse("3:45")
225
Upvotes: 2
Reputation: 160321
pry(main)> a = "3:45".split(":")
=> ["3", "45"]
pry(main)> a[0].to_i*60 + a[1].to_i
=> 225
(Wrapped up in a method, of course.)
Upvotes: 0