Comparing times only, without dates?

后端 未结 8 1403
不知归路
不知归路 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:08

    Try converting the Time into a number and strip off the days. Since the Time is represented as a number of seconds since the UNIX Epoch with the decimal being a fraction of the second, you can convert this number to a number of days with the fraction being a fraction of a day.

    Day based number = Ruby Time Number / 60 / 60 / 24

    You can then use the modulus operator to strip the day portion so all you have left to compare is the time. So you want something like this:

    def is_open?(time)
      open_h=Time.parse('2012-02-02 02:30:00 UTC')
      close_h=Time.parse('2012-02-02 10:00:00 UTC')
      (((time.to_r / 60 / 60 / 24) % 1) >= ((open_h.to_r / 60 / 60 / 24) % 1)) && (((time.to_r / 60 / 60 / 24) % 1) <= ((close_h.to_r / 60 / 60 / 24) % 1))
    end
    
    is_open? (Time.parse('2013-01-01 09:58:00 UTC'))
    => true
    is_open? (Time.parse('2013-01-01 12:58:00 UTC'))
    => false
    

提交回复
热议问题