1

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 
Rilcon42
  • 9,584
  • 18
  • 83
  • 167

3 Answers3

3

Pure Ruby way (without including rails's active_support) :

You just need to take off fractions of a day.

one_hour_ago_time = (DateTime.now - (1.0/24))
  • 1.0 = one day
  • 1.0/24 = 1 hour
  • 1.0/(24*60) = 1 minute
  • 1.0/(24*60*60) = 1 second
Gagan Gami
  • 10,121
  • 1
  • 29
  • 55
1

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
jan.zikan
  • 1,308
  • 10
  • 14
0

You can also try this:

current_time = DateTime.now.strftime("%Y-%m-%d %H:%M:%S")

last_time = (DateTime.now - (1.0/24)).strftime("%Y-%m-%d %H:%M:%S")

last_time.upto(current_time) {|date| puts date }
bipin52165
  • 168
  • 8