Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

ios - PFQuery by date

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.

 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
 [dateFormat setDateFormat:@"YYY-MM-dd"];
 NSString *today;
 today = [dateFormat stringFromDate:[NSDate date]];

 PFQuery *query = [PFQuery queryWithClassName:@"Booking"];

 [query whereKey:@"nextAppointment" equalTo:today];

 [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) { etc etc...

The field nextAppointment is set as a date using the Parse website. Any help would be appreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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...
    }
}];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...