Comparing times only, without dates?

后端 未结 8 1344
不知归路
不知归路 2021-01-31 16:30

I need to write a method that will check if Time.now is in between the open hours and the close hours of a shop.

The open and close hours are saved as a Tim

8条回答
  •  青春惊慌失措
    2021-01-31 17:10

    Instead of trying to compare the point of time directly, you can compare their offsets from a common reference (e.g. midnight). You might need to make sure all times are using the same time zone, depending on your use case.

    In Rails, this can be done easily with one of the helpers such as #seconds_since_midnight:

    #given
    opening_hour = DateTime.new(2012,2,2,2,30,0)
    
    #compare
    now = DateTime.now.in_time_zone('UTC')
    opening_hour_since_midnight = opening_hour.seconds_since_midnight
    now_since_midnight = now.seconds_since_midnight
    p 'shop opened' if now_since_midnight > opening_hour_since_midnight
    

提交回复
热议问题