Rilcon42 Rilcon42 - 3 months ago 4
Ruby Question

tell if DateTime is within one hour of current time

My goal is to stop the loop if

dte
is within 1 hour of the current time. Is there a "ruby way" to do this?

#THIS IS AN INFINITE LOOP, DONT RUN THIS
dte=DateTime.strptime("2000-01-01 21:00:00", '%Y-%m-%d %H:%M:%S')
while(dte<(DateTime.now.to_time-1).to_datetime)
#increments dte by one hour, not shown here
end

Answer

If you really need to use the DateTime, then you are doing it the right way.

Subtract n hours from a DateTime in Ruby

You can also do:

require 'time'
time = Time.parse('2000-01-01 21:00:00')
while time < Time.now - 3600 do
  ...
end

You can be more efficient using active_support core extensions.

require 'active_support/core_ext/numeric/time'    
while time < Time.now - 1.hour do
  ...
end

Even better

while time < 1.hour.ago do
  ...
end
Comments