Comparing times only, without dates?

后端 未结 8 1223
不知归路
不知归路 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
    
    0 讨论(0)
  • 2021-01-31 17:13

    You can compare only time in rails without date part like:--- Here post_review is table and we are getting only these record of post_review which are created_at between 10 am ---5pm in any date

    post_review.where("(created_at::time >= :start_time) AND (created_at::time <= :end_time)", 
        start_time: Time.parse("10 am").strftime("%r"),
        end_time:   Time.parse("5 pm").strftime("%r")
     )
    
    0 讨论(0)
提交回复
热议问题