0

I am using this code to compare times:

(time1.to_i - time2.to_i).abs < 5 

The intention is that if two times are measured within 5 seconds from each other, they will be equal. I'm using it to compare updating of records, so 5 seconds is acceptable as a buffer, and stops the code returning false when the records are only splitseconds apart.

Is there a better way to do this?

1
  • There's a gem called time_difference. It isn't actively maintained, but it's easy to follow and incorporate. It gives you syntax like this: TimeDifference.between(start_time, end_time).in_years. Commented May 22, 2017 at 1:42

1 Answer 1

1

In Ruby, you can subtract two Time objects directly to get the difference in seconds. Rails provides some convenience helpers on integers to convert them into seconds as well:

(time1 - time2).abs < 5.seconds 

If you know that time2 always comes after time1, you can get rid of the abs:

time2 - time1 < 5.seconds 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.