Home > Enterprise >  Compare times on separate dates in Ruby/Rails?
Compare times on separate dates in Ruby/Rails?

Time:09-14

I have 3 different TimeWithZone objects:

from = Mon, 20 Apr 2020 00:00:00.000000000 UTC  00:00
to = Mon, 20 Apr 2020 23:59:59.000000000 UTC  00:00

event = Sat, 01 Jan 2000 07:00:00.000000000 UTC  00:00

I don't care about the dates. All I need is to be able to see if the time of event falls within the time bounds of from and to.

In the example above, the event does fall within the time bounds.

I've tried converting the from and to to just their time values using strftime and then converting them back to times with #to_time, but this causes the hours and minutes to change.

Any ideas?

CodePudding user response:

You can format every value and than compare them

from_time, to_time, event_time = [from, to, event].map { |t| t.strftime("%H%M%S%N") }

event_time.between?(from_time, to_time)

CodePudding user response:

event.between?(from, to) will return true if between and false if not

  • Related