Shpigford
Shpigford

Reputation: 25378

How to convert amount of time into seconds?

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

Answers (5)

Marek Příhoda
Marek Příhoda

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

Michael Durrant
Michael Durrant

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

Emily
Emily

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

user1976
user1976

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

Dave Newton
Dave Newton

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

Related Questions