简体   繁体   中英

Trying to filter datetime fields based on time only

I'm having some trouble figuring out how to build a scope for a specific type of query I'm trying to do.

Basically I have an Availabilities model which has a start_time and end_time datetime columns.

I have a start and end time dropdown in my view which returns this query on search:

 "availabilities"."start_time" >= '2015-10-27 00:00:00.000000' AND "availabilities"."end_time" <= '2015-10-31 00:00:00.000000'

I've been asked to add a new time range filter:

Morning (6am - 12pm)
Afternoon (12-6pm)
Night (6pm - 12am )

I'm not sure how I'd approach that. This is what an availability record looks like:

   <Availability:0x000000065b2bf0> {
                 :id => 1,
         :start_time => Sat, 21 Nov 2015 11:00:00 UTC +00:00,
           :end_time => Sat, 21 Nov 2015 12:00:00 UTC +00:00,
              :price => 24.1,
           :discount => 20.0,
         :created_at => Fri, 23 Oct 2015 21:31:49 UTC +00:00,
         :updated_at => Fri, 23 Oct 2015 21:31:49 UTC +00:00,
        :facility_id => 1,
         :booking_id => nil
    }

So I need to filter only on the time portion of the field but am not sure how to approach this.

How to use a part of a timestamp in a query depends somewhat on what database you're using. For example, with PostgreSQL you could use the extract function to group or filter things based on the time of day.

If you're unsure how to do that, you could also look at the groupdate gem ( https://github.com/ankane/groupdate ) which appears to do what you're looking for in a more database agnostic way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM