views:

78

answers:

3
t = Time.now
d = 10.minutes.from_now

Using these two variables, how do I output a timer like 00:10:00?

As d counts down, the timer would show 00:09:59, 00:09:58, etc.

Note: I'd formatting uses Rails datetime format method somehow.

+2  A: 

I think that this should do what you want.

def formatted_duration time_in_seconds
  Time.at(time_in_seconds).gmtime.strftime('%R:%S')
end

t = Time.now
d = t+ 10.minutes #10.minutes.from_now 
puts formatted_duration(d.to_i - t.to_i)
Randy Simon
+1 for '%R:%S'. Thanks, Randy Simon :)
macek
A: 

This ended up working best for me:

def timer(end_time)
  Time.zone.at(end_time-Time.now).strftime("%R:%S")
end
macek
A: 

This might be faster:

def timer(end_time)
  d = (end_time - Time.now).to_i
  return "#{(d/60)%60}:#{d%60}"
end

No in your irb console:

>> t = Time.now + 15.minutes
=> Thu Mar 18 11:32:58 -0700 2010
>> timer(t)
=> "14:54"
>> timer(t)
=> "14:52"
>> timer(t)
=> "14:50"
KandadaBoggu
I like where this is going but it needs to display seconds too!
macek
It displays minutes and seconds, read the amended answer.
KandadaBoggu