PFQuery by date

折月煮酒 提交于 2019-11-29 12:30:55

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...
    }
}];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!