Rails 3.1: Querying Postgres for records within a time range

后端 未结 1 1673
日久生厌
日久生厌 2020-12-18 16:12

In my app I have a Person model. Each Person has an attribute time_zone that specifies their default time zone. I also have an E

相关标签:
1条回答
  • 2020-12-18 16:29

    You're losing track of your timezones when you call to_date so don't do that:

    @today    = Time.now.in_time_zone(@person.time_zone).midnight.utc
    @tomorrow = @today + 1.day
    

    When you some_date.to_datetime, you get a DateTime instance that is in UTC so the result of something like this:

    Time.now.in_time_zone(@person.time_zone).midnight.to_date.to_datetime
    

    will have a time-of-day of 00:00:00 and a time zone of UTC; the 00:00:00 is the correct time-of-day in @person.time_zone but not right for UTC (unless, of course, @person is in in the +0 time zone).

    And you could simplify your query with overlaps:

    where(
        '(start_time, end_time) overlaps (timestamp :today, timestamp :tomorrow)',
        :today => @today, :tomorrow => @tomorrow
    )
    

    Note that overlaps works with half-open intervals:

    Each time period is considered to represent the half-open interval start <= time < end, unless start and end are equal in which case it represents that single time instant.

    0 讨论(0)
提交回复
热议问题