Home > Back-end >  Approximate comparison of 2 Ruby DateTimes
Approximate comparison of 2 Ruby DateTimes

Time:04-22

I have 2 DateTimes and I want to check if they're roughly 24 hours apart, plus or minus a small amount, say 5 minutes. Is there a built in way to do this?

CodePudding user response:

There is not, but it is easy enough:

(-5 * 60 .. 5 * 60).include?((t2 - t1).abs - 24 * 3600)

"is the absolute difference between the two dates, when you subtract a full day, within plus or minus five minutes?"

CodePudding user response:

Version 1: Works for both DateTime and Time. Converts everything to seconds.

def time_apart_within_drift?(t1, t2, diff: 24*60*60, drift: 5*60)
  (t1.to_i - t2.to_i).abs <= diff   drift
end

As per the Ruby Style Guide, you should almost always use Time instead of DateTime. A Time object can still include the date, and it will make your calculations much cleaner.

This is because subtracting two DateTime objects gives you the difference in days as a Rational object, whereas subtracting two Time objects gives you the difference in seconds as a Float.

This allows you to write your function like so:

def time_apart_within_drift?(t1, t2, diff: 24*60*60, drift: 5*60)
  (t1 - t2).abs <= diff   drift
end

# true
time_apart_within_drift?(Time.new(2020,3,5), Time.new(2020,3,4))

# true
time_apart_within_drift?(Time.new(2020,3,5), Time.new(2020,3,3,23,57))

# false
time_apart_within_drift?(Time.new(2020,3,5), Time.new(2020,3,3,23,47))

If using Time as well as rails and/or activesupport, the args can be made more readable using Duration objects:

def time_apart_within_drift?(t1, t2, diff: 24.hours, drift: 5.minutes)
  (t1 - t2).abs <= diff   drift
end
  •  Tags:  
  • ruby
  • Related