I found a countdown timer on this site which works well in linux, but I need this exact thing done in Ruby. I am new to ruby so having trouble figuring this out.
==Linux version==
seconds=20; date1=$((`date +%s` + $seconds));
while [ "$date1" -ne `date +%s` ]; do
echo -ne "$(date -u --date @$(($date1 - `date +%s` )) +%H:%M:%S)\r";
done
So far I have tried this which does not give me the desired output
t = Time.now
seconds = 30
date1 = (t + seconds)
while t != date1
puts t
sleep 1
end
This gives an output like this which A) is not counting down and B) has date added which I don't want.
2015-05-28 09:57:18 -0500
2015-05-28 09:57:18 -0500
2015-05-28 09:57:18 -0500
2015-05-28 09:57:18 -0500
I want it to output like the linux version which looks like this
00:00:30
00:00:29
00:00:28
Try this, if you just need the output and don't use any Time related info :
30.downto(0) do |i|
puts "00:00:#{'%02d' % i}"
sleep 1
end
With time (1st draft) :
t = Time.new(0)
countdown_time_in_seconds = 300 # change this value
countdown_time_in_seconds.downto(0) do |seconds|
puts (t + seconds).strftime('%H:%M:%S')
sleep 1
end
Try this:
def countdown(seconds)
date1 = Time.now + seconds
while Time.now < date1
t = Time.at(date1.to_i - Time.now.to_i)
p t.strftime('%H:%M:%S')
sleep 1
end
end
This is tacking an extra hour to the time...not sure why that is, but the big thing is to use Time.now
the whole way through.
edit if you don't want to use it as a method, you can just use the code inside:
date1 = Time.now + 5 # your time here
while Time.now < date1
t = Time.at(date1.to_i - Time.now.to_i)
p t.strftime('%H:%M:%S')
sleep 1
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With