4

A parse object in my database has a date field that i have to use as filter to show the user some results from a specific day. I'm asking the user to choose a day with a UIPickerDate and them i'm creating a query with this constraint:

        [query whereKey:@"meetingDateAndTime" equalTo:appDelegate.meetingDateAndTime]; // appDelegate.meetingDateAndTime represent the UIPickerDate date

The problem is that even if i set the UIPickerDate with UIDatePickerModeDate the date contains also the time, so the query doesn't retrieve anything. I then thought to create two other dates, the first 1 day before with the time at 23:59 and the other 1 day after with time at 00:00 and then add two parse constraint, like this:

    NSDate *choosedDate = appDelegate.meetingDateAndTime;

    NSDateComponents *dayComponentPrev = [[NSDateComponents alloc] init];
    NSDateComponents *dayComponentNext = [[NSDateComponents alloc] init];
    dayComponentPrev.day = -1;
    dayComponentNext.day = +1;
    NSCalendar *theCalendar = [NSCalendar currentCalendar];
    NSDate *prevDate = [theCalendar dateByAddingComponents:dayComponentPrev toDate:choosedDate options:0];
    NSDate *nextDate = [theCalendar dateByAddingComponents:dayComponentNext toDate:choosedDate options:0];

    NSDateComponents *componentsPrev = [theCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:prevDate];
    [componentsPrev setHour:23];
    [componentsPrev setMinute:59];
    NSDate *prevOk = [theCalendar dateFromComponents:componentsPrev];

    NSDateComponents *componentsNext = [theCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:nextDate];
    [componentsNext setHour:0];
    [componentsNext setMinute:0];
    NSDate *nextOk = [theCalendar dateFromComponents:componentsNext];

    [query whereKey:@"meetingDateAndTime" greaterThan:prevOk];
    [query whereKey:@"meetingDateAndTime" lessThan:nextOk];

The solution works but i'm wondering if there is a more elegant way to do this. Being new to IOS and Parse i tend to over-complicate things...Any suggestion?

Diego
  • 366
  • 3
  • 18

1 Answers1

4

No, this is the best solution.

What you could do is make sure that any meeting objects that you create always have the same time. A date is not really a date it's a point in time so you can't have a date without a time.

So it doesn't make sense to get everything where the date equals today because there is no date "today".

So, if you set the time of each event to be 00:00 on the selected day then you could query all meetings at 00:00 on a selected day.

Otherwise, the query that you have done will be the best.

Fogmeister
  • 76,236
  • 42
  • 207
  • 306
  • Unfortunately I cannot set the time of all the objects because it is necessary to the app. Thank you anyway, i'm glad for once i found the right solution XD. – Diego Aug 04 '14 at 18:00