PFQuery by date

前端 未结 1 478
隐瞒了意图╮
隐瞒了意图╮ 2020-12-20 07:44

I\'m trying to search for all results that contain a certain date (no time) with a PFQuery. I can\'t seem to figure out why it is not working. My code I am using is below.

相关标签:
1条回答
  • 2020-12-20 08:01

    An NSDate object and the Parse.com Date field both have an exact time that includes hours and minutes. This means that if you are looking for an appointment that takes place on a certain day, you are actually searching a date range: the range from 12:00am until 11:59pm of that particular day.

    If you create an NSDate with no explicit hours and minutes, Parse doesn't know you mean "all dates on that day" - it interprets it by populating hours and minutes and searching for an exact time. You get around this with the date range search.

    Here is an example of how to do this from one of my apps, modified for your purposes:

    //Create two dates for this morning at 12:00am and tonight at 11:59pm
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:now];
    [components setHour:0];
    [components setMinute:0];
    [components setSecond:1];
    NSDate *morningStart = [calendar dateFromComponents:components];
    
    [components setHour:23];
    [components setMinute:59];
    [components setSecond:59];
    NSDate *tonightEnd = [calendar dateFromComponents:components];
    
    PFQuery *query = [PFQuery queryWithClassName:@"Booking"];
    [query whereKey:@"nextAppointment" greaterThan:morningStart];
    [query whereKey:@"nextAppointment" lessThan:tonightEnd];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            //Etc...
        }
    }];
    
    0 讨论(0)
提交回复
热议问题