NSPredicate: filtering objects by day of NSDate property












117














I have a Core Data model with an NSDate property. I want to filter the database by day. I assume the solution will involve an NSPredicate, but I'm not sure how to put it all together.



I know how to compare the day of two NSDates using NSDateComponents and NSCalendar, but how do I filter it with an NSPredicate?



Perhaps I need to create a category on my NSManagedObject subclass that can return a bare date with just the year, month and day. Then I could compare that in an NSPredicate. Is this your recommendation, or is there something simpler?










share|improve this question





























    117














    I have a Core Data model with an NSDate property. I want to filter the database by day. I assume the solution will involve an NSPredicate, but I'm not sure how to put it all together.



    I know how to compare the day of two NSDates using NSDateComponents and NSCalendar, but how do I filter it with an NSPredicate?



    Perhaps I need to create a category on my NSManagedObject subclass that can return a bare date with just the year, month and day. Then I could compare that in an NSPredicate. Is this your recommendation, or is there something simpler?










    share|improve this question



























      117












      117








      117


      48





      I have a Core Data model with an NSDate property. I want to filter the database by day. I assume the solution will involve an NSPredicate, but I'm not sure how to put it all together.



      I know how to compare the day of two NSDates using NSDateComponents and NSCalendar, but how do I filter it with an NSPredicate?



      Perhaps I need to create a category on my NSManagedObject subclass that can return a bare date with just the year, month and day. Then I could compare that in an NSPredicate. Is this your recommendation, or is there something simpler?










      share|improve this question















      I have a Core Data model with an NSDate property. I want to filter the database by day. I assume the solution will involve an NSPredicate, but I'm not sure how to put it all together.



      I know how to compare the day of two NSDates using NSDateComponents and NSCalendar, but how do I filter it with an NSPredicate?



      Perhaps I need to create a category on my NSManagedObject subclass that can return a bare date with just the year, month and day. Then I could compare that in an NSPredicate. Is this your recommendation, or is there something simpler?







      objective-c core-data nsdate nspredicate nsfetchedresultscontroller






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 3 '12 at 15:08









      Florian Pilz

      3,95931628




      3,95931628










      asked Dec 27 '09 at 6:07









      Jonathan Sterling

      14.5k126078




      14.5k126078
























          8 Answers
          8






          active

          oldest

          votes


















          186














          Given a NSDate * startDate and endDate and a NSManagedObjectContext * moc:



          NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date >= %@) AND (date <= %@)", startDate, endDate];
          NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
          [request setEntity:[NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:moc]];
          [request setPredicate:predicate];

          NSError *error = nil;
          NSArray *results = [moc executeFetchRequest:request error:&error];





          share|improve this answer

















          • 3




            what if we have only one date?
            – Wasim
            Sep 14 '11 at 9:55






          • 3




            Looks like you can use ==. Though if you're searching by day, remember that NSDate is a date-and-time -- you might want to use a midnight-to-midnight range.
            – jlstrecker
            Oct 17 '11 at 15:45








          • 1




            Example on how to also setup startDate and endDate, see my answer below
            – d.ennis
            Nov 13 '11 at 22:13










          • @jlstrecker can u show me an example how to use a midnight to midnight range. for example: i have 2 same days but different timing. and i want to filter by day(i dont care about the timing). How can i do that?
            – iosMentalist
            Sep 7 '12 at 13:47






          • 3




            @Shady In the above example, you could set startDate to 2012-09-17 0:00:00 and endDate to 2012-09-18 0:00:00 and the predicate to startDate <= date < endDate. That would catch all times on 2012-09-17.
            – jlstrecker
            Sep 17 '12 at 23:34





















          61














          Example on how to also set up startDate and endDate to the above given answer:



          ...

          NSCalendar *calendar = [NSCalendar currentCalendar];
          NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth ) fromDate:[NSDate date]];
          //create a date with these components
          NSDate *startDate = [calendar dateFromComponents:components];
          [components setMonth:1];
          [components setDay:0]; //reset the other components
          [components setYear:0]; //reset the other components
          NSDate *endDate = [calendar dateByAddingComponents:components toDate:startDate options:0];
          predicate = [NSPredicate predicateWithFormat:@"((date >= %@) AND (date < %@)) || (date = nil)",startDate,endDate];

          ...


          Here I was searching for all entries within one month. It's worth to mention, that this example also shows how to search 'nil' date-entires.






          share|improve this answer



















          • 1




            Saved my Day :)
            – Xeieshan
            May 1 '14 at 11:59



















          10














          In Swift I got something similar to:



                  let dateFormatter = NSDateFormatter()
          dateFormatter.dateFormat = "yyyy-MM-dd"
          let date = dateFormatter.dateFromString(predicate)
          let calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
          let components = calendar!.components(
          NSCalendarUnit.CalendarUnitYear |
          NSCalendarUnit.CalendarUnitMonth |
          NSCalendarUnit.CalendarUnitDay |
          NSCalendarUnit.CalendarUnitHour |
          NSCalendarUnit.CalendarUnitMinute |
          NSCalendarUnit.CalendarUnitSecond, fromDate: date!)
          components.hour = 00
          components.minute = 00
          components.second = 00
          let startDate = calendar!.dateFromComponents(components)
          components.hour = 23
          components.minute = 59
          components.second = 59
          let endDate = calendar!.dateFromComponents(components)
          predicate = NSPredicate(format: "day >= %@ AND day =< %@", argumentArray: [startDate!, endDate!])


          I had a hard time to discover that string interpolation "(this notation)" doesn't work for comparing dates in NSPredicate.






          share|improve this answer





















          • Thank you for this answer. Swift 3 version added below.
            – DS.
            Sep 10 '16 at 21:30



















          8














          I ported the answer from Glauco Neves to Swift 2.0 and wrapped it inside a function that receives a date and returns the NSPredicate for the corresponding day:



          func predicateForDayFromDate(date: NSDate) -> NSPredicate {
          let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
          let components = calendar!.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: date)
          components.hour = 00
          components.minute = 00
          components.second = 00
          let startDate = calendar!.dateFromComponents(components)
          components.hour = 23
          components.minute = 59
          components.second = 59
          let endDate = calendar!.dateFromComponents(components)

          return NSPredicate(format: "day >= %@ AND day =< %@", argumentArray: [startDate!, endDate!])
          }





          share|improve this answer























          • Thank you for this answer. Swift 3 version added below.
            – DS.
            Sep 10 '16 at 21:30



















          8














          Swift 3.0 extension for Date:



          extension Date{

          func makeDayPredicate() -> NSPredicate {
          let calendar = Calendar.current
          var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: self)
          components.hour = 00
          components.minute = 00
          components.second = 00
          let startDate = calendar.date(from: components)
          components.hour = 23
          components.minute = 59
          components.second = 59
          let endDate = calendar.date(from: components)
          return NSPredicate(format: "day >= %@ AND day =< %@", argumentArray: [startDate!, endDate!])
          }
          }


          Then use like:



           let fetchReq = NSFetchRequest(entityName: "MyObject")
          fetchReq.predicate = myDate.makeDayPredicate()





          share|improve this answer





























            6














            Adding to Rafael's answer (incredibly useful, thank you!), porting for Swift 3.



            func predicateForDayFromDate(date: Date) -> NSPredicate {
            let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
            var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
            components.hour = 00
            components.minute = 00
            components.second = 00
            let startDate = calendar.date(from: components)
            components.hour = 23
            components.minute = 59
            components.second = 59
            let endDate = calendar.date(from: components)

            return NSPredicate(format: "YOUR_DATE_FIELD >= %@ AND YOUR_DATE_FIELD =< %@", argumentArray: [startDate!, endDate!])
            }





            share|improve this answer





























              1














              I've recently spent some time attempting to solve this same problem and add the following to the list of alternatives to prepare start and end dates (includes updated method for iOS 8 and above)...



              NSDate *dateDay = nil;
              NSDate *dateDayStart = nil;
              NSDate *dateDayNext = nil;

              dateDay = <<USER_INPUT>>;

              dateDayStart = [[NSCalendar currentCalendar] startOfDayForDate:dateDay];

              // dateDayNext EITHER
              dateDayNext = [dateDayStart dateByAddingTimeInterval:(24 * 60 * 60)];

              // dateDayNext OR
              NSDateComponents *dateComponentDay = nil;
              dateComponentDay = [[NSDateComponents alloc] init];
              [dateComponentDay setDay:1];
              dateDayNext = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponentDay
              toDate:dateDayStart
              options:NSCalendarMatchNextTime];


              ...and the NSPredicate for the Core Data NSFetchRequest (as already shown above in other answers)...



              [NSPredicate predicateWithFormat:@"(dateAttribute >= %@) AND (dateAttribute < %@)", dateDayStart, dateDayNext]]





              share|improve this answer





























                0














                For me this is worked.



                NSCalendar *calendar = [NSCalendar currentCalendar];
                NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit ) fromDate:[NSDate date]];
                //create a date with these components
                NSDate *startDate = [calendar dateFromComponents:components];
                [components setMonth:0];
                [components setDay:0]; //reset the other components
                [components setYear:0]; //reset the other components
                NSDate *endDate = [calendar dateByAddingComponents:components toDate:startDate options:0];

                startDate = [NSDate date];
                endDate = [startDate dateByAddingTimeInterval:-(7 * 24 * 60 * 60)];//change here

                NSString *startTimeStamp = [[NSNumber numberWithInt:floor([endDate timeIntervalSince1970])] stringValue];
                NSString *endTimeStamp = [[NSNumber numberWithInt:floor([startDate timeIntervalSince1970])] stringValue];


                NSPredicate *predicate = [NSPredicate predicateWithFormat:@"((paidDate1 >= %@) AND (paidDate1 < %@))",startTimeStamp,endTimeStamp];
                NSLog(@"predicate is %@",predicate);
                totalArr = [completeArray filteredArrayUsingPredicate:predicate];
                [self filterAndPopulateDataBasedonIndex];
                [self.tableviewObj reloadData];
                NSLog(@"result is %@",totalArr);


                I have filtered array from current date to 7 days back. I mean I am getting one week data from current date. This should work.



                Note: I am converting date which is coming with milli seconds by 1000, and comparing after. Let me know if you need any clarity.






                share|improve this answer





















                • In your answer completeArray is it having Array of dictionary or dataModel I want to apply on DataModel.
                  – Sumeet Mourya
                  Jun 14 '17 at 6:02











                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1965331%2fnspredicate-filtering-objects-by-day-of-nsdate-property%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                8 Answers
                8






                active

                oldest

                votes








                8 Answers
                8






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                186














                Given a NSDate * startDate and endDate and a NSManagedObjectContext * moc:



                NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date >= %@) AND (date <= %@)", startDate, endDate];
                NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
                [request setEntity:[NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:moc]];
                [request setPredicate:predicate];

                NSError *error = nil;
                NSArray *results = [moc executeFetchRequest:request error:&error];





                share|improve this answer

















                • 3




                  what if we have only one date?
                  – Wasim
                  Sep 14 '11 at 9:55






                • 3




                  Looks like you can use ==. Though if you're searching by day, remember that NSDate is a date-and-time -- you might want to use a midnight-to-midnight range.
                  – jlstrecker
                  Oct 17 '11 at 15:45








                • 1




                  Example on how to also setup startDate and endDate, see my answer below
                  – d.ennis
                  Nov 13 '11 at 22:13










                • @jlstrecker can u show me an example how to use a midnight to midnight range. for example: i have 2 same days but different timing. and i want to filter by day(i dont care about the timing). How can i do that?
                  – iosMentalist
                  Sep 7 '12 at 13:47






                • 3




                  @Shady In the above example, you could set startDate to 2012-09-17 0:00:00 and endDate to 2012-09-18 0:00:00 and the predicate to startDate <= date < endDate. That would catch all times on 2012-09-17.
                  – jlstrecker
                  Sep 17 '12 at 23:34


















                186














                Given a NSDate * startDate and endDate and a NSManagedObjectContext * moc:



                NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date >= %@) AND (date <= %@)", startDate, endDate];
                NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
                [request setEntity:[NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:moc]];
                [request setPredicate:predicate];

                NSError *error = nil;
                NSArray *results = [moc executeFetchRequest:request error:&error];





                share|improve this answer

















                • 3




                  what if we have only one date?
                  – Wasim
                  Sep 14 '11 at 9:55






                • 3




                  Looks like you can use ==. Though if you're searching by day, remember that NSDate is a date-and-time -- you might want to use a midnight-to-midnight range.
                  – jlstrecker
                  Oct 17 '11 at 15:45








                • 1




                  Example on how to also setup startDate and endDate, see my answer below
                  – d.ennis
                  Nov 13 '11 at 22:13










                • @jlstrecker can u show me an example how to use a midnight to midnight range. for example: i have 2 same days but different timing. and i want to filter by day(i dont care about the timing). How can i do that?
                  – iosMentalist
                  Sep 7 '12 at 13:47






                • 3




                  @Shady In the above example, you could set startDate to 2012-09-17 0:00:00 and endDate to 2012-09-18 0:00:00 and the predicate to startDate <= date < endDate. That would catch all times on 2012-09-17.
                  – jlstrecker
                  Sep 17 '12 at 23:34
















                186












                186








                186






                Given a NSDate * startDate and endDate and a NSManagedObjectContext * moc:



                NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date >= %@) AND (date <= %@)", startDate, endDate];
                NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
                [request setEntity:[NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:moc]];
                [request setPredicate:predicate];

                NSError *error = nil;
                NSArray *results = [moc executeFetchRequest:request error:&error];





                share|improve this answer












                Given a NSDate * startDate and endDate and a NSManagedObjectContext * moc:



                NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date >= %@) AND (date <= %@)", startDate, endDate];
                NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
                [request setEntity:[NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:moc]];
                [request setPredicate:predicate];

                NSError *error = nil;
                NSArray *results = [moc executeFetchRequest:request error:&error];






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Dec 27 '09 at 9:17









                diciu

                26.5k34461




                26.5k34461








                • 3




                  what if we have only one date?
                  – Wasim
                  Sep 14 '11 at 9:55






                • 3




                  Looks like you can use ==. Though if you're searching by day, remember that NSDate is a date-and-time -- you might want to use a midnight-to-midnight range.
                  – jlstrecker
                  Oct 17 '11 at 15:45








                • 1




                  Example on how to also setup startDate and endDate, see my answer below
                  – d.ennis
                  Nov 13 '11 at 22:13










                • @jlstrecker can u show me an example how to use a midnight to midnight range. for example: i have 2 same days but different timing. and i want to filter by day(i dont care about the timing). How can i do that?
                  – iosMentalist
                  Sep 7 '12 at 13:47






                • 3




                  @Shady In the above example, you could set startDate to 2012-09-17 0:00:00 and endDate to 2012-09-18 0:00:00 and the predicate to startDate <= date < endDate. That would catch all times on 2012-09-17.
                  – jlstrecker
                  Sep 17 '12 at 23:34
















                • 3




                  what if we have only one date?
                  – Wasim
                  Sep 14 '11 at 9:55






                • 3




                  Looks like you can use ==. Though if you're searching by day, remember that NSDate is a date-and-time -- you might want to use a midnight-to-midnight range.
                  – jlstrecker
                  Oct 17 '11 at 15:45








                • 1




                  Example on how to also setup startDate and endDate, see my answer below
                  – d.ennis
                  Nov 13 '11 at 22:13










                • @jlstrecker can u show me an example how to use a midnight to midnight range. for example: i have 2 same days but different timing. and i want to filter by day(i dont care about the timing). How can i do that?
                  – iosMentalist
                  Sep 7 '12 at 13:47






                • 3




                  @Shady In the above example, you could set startDate to 2012-09-17 0:00:00 and endDate to 2012-09-18 0:00:00 and the predicate to startDate <= date < endDate. That would catch all times on 2012-09-17.
                  – jlstrecker
                  Sep 17 '12 at 23:34










                3




                3




                what if we have only one date?
                – Wasim
                Sep 14 '11 at 9:55




                what if we have only one date?
                – Wasim
                Sep 14 '11 at 9:55




                3




                3




                Looks like you can use ==. Though if you're searching by day, remember that NSDate is a date-and-time -- you might want to use a midnight-to-midnight range.
                – jlstrecker
                Oct 17 '11 at 15:45






                Looks like you can use ==. Though if you're searching by day, remember that NSDate is a date-and-time -- you might want to use a midnight-to-midnight range.
                – jlstrecker
                Oct 17 '11 at 15:45






                1




                1




                Example on how to also setup startDate and endDate, see my answer below
                – d.ennis
                Nov 13 '11 at 22:13




                Example on how to also setup startDate and endDate, see my answer below
                – d.ennis
                Nov 13 '11 at 22:13












                @jlstrecker can u show me an example how to use a midnight to midnight range. for example: i have 2 same days but different timing. and i want to filter by day(i dont care about the timing). How can i do that?
                – iosMentalist
                Sep 7 '12 at 13:47




                @jlstrecker can u show me an example how to use a midnight to midnight range. for example: i have 2 same days but different timing. and i want to filter by day(i dont care about the timing). How can i do that?
                – iosMentalist
                Sep 7 '12 at 13:47




                3




                3




                @Shady In the above example, you could set startDate to 2012-09-17 0:00:00 and endDate to 2012-09-18 0:00:00 and the predicate to startDate <= date < endDate. That would catch all times on 2012-09-17.
                – jlstrecker
                Sep 17 '12 at 23:34






                @Shady In the above example, you could set startDate to 2012-09-17 0:00:00 and endDate to 2012-09-18 0:00:00 and the predicate to startDate <= date < endDate. That would catch all times on 2012-09-17.
                – jlstrecker
                Sep 17 '12 at 23:34















                61














                Example on how to also set up startDate and endDate to the above given answer:



                ...

                NSCalendar *calendar = [NSCalendar currentCalendar];
                NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth ) fromDate:[NSDate date]];
                //create a date with these components
                NSDate *startDate = [calendar dateFromComponents:components];
                [components setMonth:1];
                [components setDay:0]; //reset the other components
                [components setYear:0]; //reset the other components
                NSDate *endDate = [calendar dateByAddingComponents:components toDate:startDate options:0];
                predicate = [NSPredicate predicateWithFormat:@"((date >= %@) AND (date < %@)) || (date = nil)",startDate,endDate];

                ...


                Here I was searching for all entries within one month. It's worth to mention, that this example also shows how to search 'nil' date-entires.






                share|improve this answer



















                • 1




                  Saved my Day :)
                  – Xeieshan
                  May 1 '14 at 11:59
















                61














                Example on how to also set up startDate and endDate to the above given answer:



                ...

                NSCalendar *calendar = [NSCalendar currentCalendar];
                NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth ) fromDate:[NSDate date]];
                //create a date with these components
                NSDate *startDate = [calendar dateFromComponents:components];
                [components setMonth:1];
                [components setDay:0]; //reset the other components
                [components setYear:0]; //reset the other components
                NSDate *endDate = [calendar dateByAddingComponents:components toDate:startDate options:0];
                predicate = [NSPredicate predicateWithFormat:@"((date >= %@) AND (date < %@)) || (date = nil)",startDate,endDate];

                ...


                Here I was searching for all entries within one month. It's worth to mention, that this example also shows how to search 'nil' date-entires.






                share|improve this answer



















                • 1




                  Saved my Day :)
                  – Xeieshan
                  May 1 '14 at 11:59














                61












                61








                61






                Example on how to also set up startDate and endDate to the above given answer:



                ...

                NSCalendar *calendar = [NSCalendar currentCalendar];
                NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth ) fromDate:[NSDate date]];
                //create a date with these components
                NSDate *startDate = [calendar dateFromComponents:components];
                [components setMonth:1];
                [components setDay:0]; //reset the other components
                [components setYear:0]; //reset the other components
                NSDate *endDate = [calendar dateByAddingComponents:components toDate:startDate options:0];
                predicate = [NSPredicate predicateWithFormat:@"((date >= %@) AND (date < %@)) || (date = nil)",startDate,endDate];

                ...


                Here I was searching for all entries within one month. It's worth to mention, that this example also shows how to search 'nil' date-entires.






                share|improve this answer














                Example on how to also set up startDate and endDate to the above given answer:



                ...

                NSCalendar *calendar = [NSCalendar currentCalendar];
                NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth ) fromDate:[NSDate date]];
                //create a date with these components
                NSDate *startDate = [calendar dateFromComponents:components];
                [components setMonth:1];
                [components setDay:0]; //reset the other components
                [components setYear:0]; //reset the other components
                NSDate *endDate = [calendar dateByAddingComponents:components toDate:startDate options:0];
                predicate = [NSPredicate predicateWithFormat:@"((date >= %@) AND (date < %@)) || (date = nil)",startDate,endDate];

                ...


                Here I was searching for all entries within one month. It's worth to mention, that this example also shows how to search 'nil' date-entires.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 13 '18 at 4:32









                Mochi

                18114




                18114










                answered Jul 16 '11 at 13:10









                d.ennis

                2,76712135




                2,76712135








                • 1




                  Saved my Day :)
                  – Xeieshan
                  May 1 '14 at 11:59














                • 1




                  Saved my Day :)
                  – Xeieshan
                  May 1 '14 at 11:59








                1




                1




                Saved my Day :)
                – Xeieshan
                May 1 '14 at 11:59




                Saved my Day :)
                – Xeieshan
                May 1 '14 at 11:59











                10














                In Swift I got something similar to:



                        let dateFormatter = NSDateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd"
                let date = dateFormatter.dateFromString(predicate)
                let calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
                let components = calendar!.components(
                NSCalendarUnit.CalendarUnitYear |
                NSCalendarUnit.CalendarUnitMonth |
                NSCalendarUnit.CalendarUnitDay |
                NSCalendarUnit.CalendarUnitHour |
                NSCalendarUnit.CalendarUnitMinute |
                NSCalendarUnit.CalendarUnitSecond, fromDate: date!)
                components.hour = 00
                components.minute = 00
                components.second = 00
                let startDate = calendar!.dateFromComponents(components)
                components.hour = 23
                components.minute = 59
                components.second = 59
                let endDate = calendar!.dateFromComponents(components)
                predicate = NSPredicate(format: "day >= %@ AND day =< %@", argumentArray: [startDate!, endDate!])


                I had a hard time to discover that string interpolation "(this notation)" doesn't work for comparing dates in NSPredicate.






                share|improve this answer





















                • Thank you for this answer. Swift 3 version added below.
                  – DS.
                  Sep 10 '16 at 21:30
















                10














                In Swift I got something similar to:



                        let dateFormatter = NSDateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd"
                let date = dateFormatter.dateFromString(predicate)
                let calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
                let components = calendar!.components(
                NSCalendarUnit.CalendarUnitYear |
                NSCalendarUnit.CalendarUnitMonth |
                NSCalendarUnit.CalendarUnitDay |
                NSCalendarUnit.CalendarUnitHour |
                NSCalendarUnit.CalendarUnitMinute |
                NSCalendarUnit.CalendarUnitSecond, fromDate: date!)
                components.hour = 00
                components.minute = 00
                components.second = 00
                let startDate = calendar!.dateFromComponents(components)
                components.hour = 23
                components.minute = 59
                components.second = 59
                let endDate = calendar!.dateFromComponents(components)
                predicate = NSPredicate(format: "day >= %@ AND day =< %@", argumentArray: [startDate!, endDate!])


                I had a hard time to discover that string interpolation "(this notation)" doesn't work for comparing dates in NSPredicate.






                share|improve this answer





















                • Thank you for this answer. Swift 3 version added below.
                  – DS.
                  Sep 10 '16 at 21:30














                10












                10








                10






                In Swift I got something similar to:



                        let dateFormatter = NSDateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd"
                let date = dateFormatter.dateFromString(predicate)
                let calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
                let components = calendar!.components(
                NSCalendarUnit.CalendarUnitYear |
                NSCalendarUnit.CalendarUnitMonth |
                NSCalendarUnit.CalendarUnitDay |
                NSCalendarUnit.CalendarUnitHour |
                NSCalendarUnit.CalendarUnitMinute |
                NSCalendarUnit.CalendarUnitSecond, fromDate: date!)
                components.hour = 00
                components.minute = 00
                components.second = 00
                let startDate = calendar!.dateFromComponents(components)
                components.hour = 23
                components.minute = 59
                components.second = 59
                let endDate = calendar!.dateFromComponents(components)
                predicate = NSPredicate(format: "day >= %@ AND day =< %@", argumentArray: [startDate!, endDate!])


                I had a hard time to discover that string interpolation "(this notation)" doesn't work for comparing dates in NSPredicate.






                share|improve this answer












                In Swift I got something similar to:



                        let dateFormatter = NSDateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd"
                let date = dateFormatter.dateFromString(predicate)
                let calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
                let components = calendar!.components(
                NSCalendarUnit.CalendarUnitYear |
                NSCalendarUnit.CalendarUnitMonth |
                NSCalendarUnit.CalendarUnitDay |
                NSCalendarUnit.CalendarUnitHour |
                NSCalendarUnit.CalendarUnitMinute |
                NSCalendarUnit.CalendarUnitSecond, fromDate: date!)
                components.hour = 00
                components.minute = 00
                components.second = 00
                let startDate = calendar!.dateFromComponents(components)
                components.hour = 23
                components.minute = 59
                components.second = 59
                let endDate = calendar!.dateFromComponents(components)
                predicate = NSPredicate(format: "day >= %@ AND day =< %@", argumentArray: [startDate!, endDate!])


                I had a hard time to discover that string interpolation "(this notation)" doesn't work for comparing dates in NSPredicate.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered May 27 '15 at 13:36









                Glauco Neves

                2,43211834




                2,43211834












                • Thank you for this answer. Swift 3 version added below.
                  – DS.
                  Sep 10 '16 at 21:30


















                • Thank you for this answer. Swift 3 version added below.
                  – DS.
                  Sep 10 '16 at 21:30
















                Thank you for this answer. Swift 3 version added below.
                – DS.
                Sep 10 '16 at 21:30




                Thank you for this answer. Swift 3 version added below.
                – DS.
                Sep 10 '16 at 21:30











                8














                I ported the answer from Glauco Neves to Swift 2.0 and wrapped it inside a function that receives a date and returns the NSPredicate for the corresponding day:



                func predicateForDayFromDate(date: NSDate) -> NSPredicate {
                let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
                let components = calendar!.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: date)
                components.hour = 00
                components.minute = 00
                components.second = 00
                let startDate = calendar!.dateFromComponents(components)
                components.hour = 23
                components.minute = 59
                components.second = 59
                let endDate = calendar!.dateFromComponents(components)

                return NSPredicate(format: "day >= %@ AND day =< %@", argumentArray: [startDate!, endDate!])
                }





                share|improve this answer























                • Thank you for this answer. Swift 3 version added below.
                  – DS.
                  Sep 10 '16 at 21:30
















                8














                I ported the answer from Glauco Neves to Swift 2.0 and wrapped it inside a function that receives a date and returns the NSPredicate for the corresponding day:



                func predicateForDayFromDate(date: NSDate) -> NSPredicate {
                let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
                let components = calendar!.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: date)
                components.hour = 00
                components.minute = 00
                components.second = 00
                let startDate = calendar!.dateFromComponents(components)
                components.hour = 23
                components.minute = 59
                components.second = 59
                let endDate = calendar!.dateFromComponents(components)

                return NSPredicate(format: "day >= %@ AND day =< %@", argumentArray: [startDate!, endDate!])
                }





                share|improve this answer























                • Thank you for this answer. Swift 3 version added below.
                  – DS.
                  Sep 10 '16 at 21:30














                8












                8








                8






                I ported the answer from Glauco Neves to Swift 2.0 and wrapped it inside a function that receives a date and returns the NSPredicate for the corresponding day:



                func predicateForDayFromDate(date: NSDate) -> NSPredicate {
                let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
                let components = calendar!.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: date)
                components.hour = 00
                components.minute = 00
                components.second = 00
                let startDate = calendar!.dateFromComponents(components)
                components.hour = 23
                components.minute = 59
                components.second = 59
                let endDate = calendar!.dateFromComponents(components)

                return NSPredicate(format: "day >= %@ AND day =< %@", argumentArray: [startDate!, endDate!])
                }





                share|improve this answer














                I ported the answer from Glauco Neves to Swift 2.0 and wrapped it inside a function that receives a date and returns the NSPredicate for the corresponding day:



                func predicateForDayFromDate(date: NSDate) -> NSPredicate {
                let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
                let components = calendar!.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: date)
                components.hour = 00
                components.minute = 00
                components.second = 00
                let startDate = calendar!.dateFromComponents(components)
                components.hour = 23
                components.minute = 59
                components.second = 59
                let endDate = calendar!.dateFromComponents(components)

                return NSPredicate(format: "day >= %@ AND day =< %@", argumentArray: [startDate!, endDate!])
                }






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited May 23 '17 at 11:54









                Community

                11




                11










                answered Dec 14 '15 at 13:15









                Rafael Bugajewski

                98821736




                98821736












                • Thank you for this answer. Swift 3 version added below.
                  – DS.
                  Sep 10 '16 at 21:30


















                • Thank you for this answer. Swift 3 version added below.
                  – DS.
                  Sep 10 '16 at 21:30
















                Thank you for this answer. Swift 3 version added below.
                – DS.
                Sep 10 '16 at 21:30




                Thank you for this answer. Swift 3 version added below.
                – DS.
                Sep 10 '16 at 21:30











                8














                Swift 3.0 extension for Date:



                extension Date{

                func makeDayPredicate() -> NSPredicate {
                let calendar = Calendar.current
                var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: self)
                components.hour = 00
                components.minute = 00
                components.second = 00
                let startDate = calendar.date(from: components)
                components.hour = 23
                components.minute = 59
                components.second = 59
                let endDate = calendar.date(from: components)
                return NSPredicate(format: "day >= %@ AND day =< %@", argumentArray: [startDate!, endDate!])
                }
                }


                Then use like:



                 let fetchReq = NSFetchRequest(entityName: "MyObject")
                fetchReq.predicate = myDate.makeDayPredicate()





                share|improve this answer


























                  8














                  Swift 3.0 extension for Date:



                  extension Date{

                  func makeDayPredicate() -> NSPredicate {
                  let calendar = Calendar.current
                  var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: self)
                  components.hour = 00
                  components.minute = 00
                  components.second = 00
                  let startDate = calendar.date(from: components)
                  components.hour = 23
                  components.minute = 59
                  components.second = 59
                  let endDate = calendar.date(from: components)
                  return NSPredicate(format: "day >= %@ AND day =< %@", argumentArray: [startDate!, endDate!])
                  }
                  }


                  Then use like:



                   let fetchReq = NSFetchRequest(entityName: "MyObject")
                  fetchReq.predicate = myDate.makeDayPredicate()





                  share|improve this answer
























                    8












                    8








                    8






                    Swift 3.0 extension for Date:



                    extension Date{

                    func makeDayPredicate() -> NSPredicate {
                    let calendar = Calendar.current
                    var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: self)
                    components.hour = 00
                    components.minute = 00
                    components.second = 00
                    let startDate = calendar.date(from: components)
                    components.hour = 23
                    components.minute = 59
                    components.second = 59
                    let endDate = calendar.date(from: components)
                    return NSPredicate(format: "day >= %@ AND day =< %@", argumentArray: [startDate!, endDate!])
                    }
                    }


                    Then use like:



                     let fetchReq = NSFetchRequest(entityName: "MyObject")
                    fetchReq.predicate = myDate.makeDayPredicate()





                    share|improve this answer












                    Swift 3.0 extension for Date:



                    extension Date{

                    func makeDayPredicate() -> NSPredicate {
                    let calendar = Calendar.current
                    var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: self)
                    components.hour = 00
                    components.minute = 00
                    components.second = 00
                    let startDate = calendar.date(from: components)
                    components.hour = 23
                    components.minute = 59
                    components.second = 59
                    let endDate = calendar.date(from: components)
                    return NSPredicate(format: "day >= %@ AND day =< %@", argumentArray: [startDate!, endDate!])
                    }
                    }


                    Then use like:



                     let fetchReq = NSFetchRequest(entityName: "MyObject")
                    fetchReq.predicate = myDate.makeDayPredicate()






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Oct 9 '16 at 13:27









                    Roni Leshes

                    199110




                    199110























                        6














                        Adding to Rafael's answer (incredibly useful, thank you!), porting for Swift 3.



                        func predicateForDayFromDate(date: Date) -> NSPredicate {
                        let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
                        var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
                        components.hour = 00
                        components.minute = 00
                        components.second = 00
                        let startDate = calendar.date(from: components)
                        components.hour = 23
                        components.minute = 59
                        components.second = 59
                        let endDate = calendar.date(from: components)

                        return NSPredicate(format: "YOUR_DATE_FIELD >= %@ AND YOUR_DATE_FIELD =< %@", argumentArray: [startDate!, endDate!])
                        }





                        share|improve this answer


























                          6














                          Adding to Rafael's answer (incredibly useful, thank you!), porting for Swift 3.



                          func predicateForDayFromDate(date: Date) -> NSPredicate {
                          let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
                          var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
                          components.hour = 00
                          components.minute = 00
                          components.second = 00
                          let startDate = calendar.date(from: components)
                          components.hour = 23
                          components.minute = 59
                          components.second = 59
                          let endDate = calendar.date(from: components)

                          return NSPredicate(format: "YOUR_DATE_FIELD >= %@ AND YOUR_DATE_FIELD =< %@", argumentArray: [startDate!, endDate!])
                          }





                          share|improve this answer
























                            6












                            6








                            6






                            Adding to Rafael's answer (incredibly useful, thank you!), porting for Swift 3.



                            func predicateForDayFromDate(date: Date) -> NSPredicate {
                            let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
                            var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
                            components.hour = 00
                            components.minute = 00
                            components.second = 00
                            let startDate = calendar.date(from: components)
                            components.hour = 23
                            components.minute = 59
                            components.second = 59
                            let endDate = calendar.date(from: components)

                            return NSPredicate(format: "YOUR_DATE_FIELD >= %@ AND YOUR_DATE_FIELD =< %@", argumentArray: [startDate!, endDate!])
                            }





                            share|improve this answer












                            Adding to Rafael's answer (incredibly useful, thank you!), porting for Swift 3.



                            func predicateForDayFromDate(date: Date) -> NSPredicate {
                            let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
                            var components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
                            components.hour = 00
                            components.minute = 00
                            components.second = 00
                            let startDate = calendar.date(from: components)
                            components.hour = 23
                            components.minute = 59
                            components.second = 59
                            let endDate = calendar.date(from: components)

                            return NSPredicate(format: "YOUR_DATE_FIELD >= %@ AND YOUR_DATE_FIELD =< %@", argumentArray: [startDate!, endDate!])
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Sep 10 '16 at 21:29









                            DS.

                            1,45232233




                            1,45232233























                                1














                                I've recently spent some time attempting to solve this same problem and add the following to the list of alternatives to prepare start and end dates (includes updated method for iOS 8 and above)...



                                NSDate *dateDay = nil;
                                NSDate *dateDayStart = nil;
                                NSDate *dateDayNext = nil;

                                dateDay = <<USER_INPUT>>;

                                dateDayStart = [[NSCalendar currentCalendar] startOfDayForDate:dateDay];

                                // dateDayNext EITHER
                                dateDayNext = [dateDayStart dateByAddingTimeInterval:(24 * 60 * 60)];

                                // dateDayNext OR
                                NSDateComponents *dateComponentDay = nil;
                                dateComponentDay = [[NSDateComponents alloc] init];
                                [dateComponentDay setDay:1];
                                dateDayNext = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponentDay
                                toDate:dateDayStart
                                options:NSCalendarMatchNextTime];


                                ...and the NSPredicate for the Core Data NSFetchRequest (as already shown above in other answers)...



                                [NSPredicate predicateWithFormat:@"(dateAttribute >= %@) AND (dateAttribute < %@)", dateDayStart, dateDayNext]]





                                share|improve this answer


























                                  1














                                  I've recently spent some time attempting to solve this same problem and add the following to the list of alternatives to prepare start and end dates (includes updated method for iOS 8 and above)...



                                  NSDate *dateDay = nil;
                                  NSDate *dateDayStart = nil;
                                  NSDate *dateDayNext = nil;

                                  dateDay = <<USER_INPUT>>;

                                  dateDayStart = [[NSCalendar currentCalendar] startOfDayForDate:dateDay];

                                  // dateDayNext EITHER
                                  dateDayNext = [dateDayStart dateByAddingTimeInterval:(24 * 60 * 60)];

                                  // dateDayNext OR
                                  NSDateComponents *dateComponentDay = nil;
                                  dateComponentDay = [[NSDateComponents alloc] init];
                                  [dateComponentDay setDay:1];
                                  dateDayNext = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponentDay
                                  toDate:dateDayStart
                                  options:NSCalendarMatchNextTime];


                                  ...and the NSPredicate for the Core Data NSFetchRequest (as already shown above in other answers)...



                                  [NSPredicate predicateWithFormat:@"(dateAttribute >= %@) AND (dateAttribute < %@)", dateDayStart, dateDayNext]]





                                  share|improve this answer
























                                    1












                                    1








                                    1






                                    I've recently spent some time attempting to solve this same problem and add the following to the list of alternatives to prepare start and end dates (includes updated method for iOS 8 and above)...



                                    NSDate *dateDay = nil;
                                    NSDate *dateDayStart = nil;
                                    NSDate *dateDayNext = nil;

                                    dateDay = <<USER_INPUT>>;

                                    dateDayStart = [[NSCalendar currentCalendar] startOfDayForDate:dateDay];

                                    // dateDayNext EITHER
                                    dateDayNext = [dateDayStart dateByAddingTimeInterval:(24 * 60 * 60)];

                                    // dateDayNext OR
                                    NSDateComponents *dateComponentDay = nil;
                                    dateComponentDay = [[NSDateComponents alloc] init];
                                    [dateComponentDay setDay:1];
                                    dateDayNext = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponentDay
                                    toDate:dateDayStart
                                    options:NSCalendarMatchNextTime];


                                    ...and the NSPredicate for the Core Data NSFetchRequest (as already shown above in other answers)...



                                    [NSPredicate predicateWithFormat:@"(dateAttribute >= %@) AND (dateAttribute < %@)", dateDayStart, dateDayNext]]





                                    share|improve this answer












                                    I've recently spent some time attempting to solve this same problem and add the following to the list of alternatives to prepare start and end dates (includes updated method for iOS 8 and above)...



                                    NSDate *dateDay = nil;
                                    NSDate *dateDayStart = nil;
                                    NSDate *dateDayNext = nil;

                                    dateDay = <<USER_INPUT>>;

                                    dateDayStart = [[NSCalendar currentCalendar] startOfDayForDate:dateDay];

                                    // dateDayNext EITHER
                                    dateDayNext = [dateDayStart dateByAddingTimeInterval:(24 * 60 * 60)];

                                    // dateDayNext OR
                                    NSDateComponents *dateComponentDay = nil;
                                    dateComponentDay = [[NSDateComponents alloc] init];
                                    [dateComponentDay setDay:1];
                                    dateDayNext = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponentDay
                                    toDate:dateDayStart
                                    options:NSCalendarMatchNextTime];


                                    ...and the NSPredicate for the Core Data NSFetchRequest (as already shown above in other answers)...



                                    [NSPredicate predicateWithFormat:@"(dateAttribute >= %@) AND (dateAttribute < %@)", dateDayStart, dateDayNext]]






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Apr 5 '16 at 4:58









                                    andrewbuilder

                                    2,2181633




                                    2,2181633























                                        0














                                        For me this is worked.



                                        NSCalendar *calendar = [NSCalendar currentCalendar];
                                        NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit ) fromDate:[NSDate date]];
                                        //create a date with these components
                                        NSDate *startDate = [calendar dateFromComponents:components];
                                        [components setMonth:0];
                                        [components setDay:0]; //reset the other components
                                        [components setYear:0]; //reset the other components
                                        NSDate *endDate = [calendar dateByAddingComponents:components toDate:startDate options:0];

                                        startDate = [NSDate date];
                                        endDate = [startDate dateByAddingTimeInterval:-(7 * 24 * 60 * 60)];//change here

                                        NSString *startTimeStamp = [[NSNumber numberWithInt:floor([endDate timeIntervalSince1970])] stringValue];
                                        NSString *endTimeStamp = [[NSNumber numberWithInt:floor([startDate timeIntervalSince1970])] stringValue];


                                        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"((paidDate1 >= %@) AND (paidDate1 < %@))",startTimeStamp,endTimeStamp];
                                        NSLog(@"predicate is %@",predicate);
                                        totalArr = [completeArray filteredArrayUsingPredicate:predicate];
                                        [self filterAndPopulateDataBasedonIndex];
                                        [self.tableviewObj reloadData];
                                        NSLog(@"result is %@",totalArr);


                                        I have filtered array from current date to 7 days back. I mean I am getting one week data from current date. This should work.



                                        Note: I am converting date which is coming with milli seconds by 1000, and comparing after. Let me know if you need any clarity.






                                        share|improve this answer





















                                        • In your answer completeArray is it having Array of dictionary or dataModel I want to apply on DataModel.
                                          – Sumeet Mourya
                                          Jun 14 '17 at 6:02
















                                        0














                                        For me this is worked.



                                        NSCalendar *calendar = [NSCalendar currentCalendar];
                                        NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit ) fromDate:[NSDate date]];
                                        //create a date with these components
                                        NSDate *startDate = [calendar dateFromComponents:components];
                                        [components setMonth:0];
                                        [components setDay:0]; //reset the other components
                                        [components setYear:0]; //reset the other components
                                        NSDate *endDate = [calendar dateByAddingComponents:components toDate:startDate options:0];

                                        startDate = [NSDate date];
                                        endDate = [startDate dateByAddingTimeInterval:-(7 * 24 * 60 * 60)];//change here

                                        NSString *startTimeStamp = [[NSNumber numberWithInt:floor([endDate timeIntervalSince1970])] stringValue];
                                        NSString *endTimeStamp = [[NSNumber numberWithInt:floor([startDate timeIntervalSince1970])] stringValue];


                                        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"((paidDate1 >= %@) AND (paidDate1 < %@))",startTimeStamp,endTimeStamp];
                                        NSLog(@"predicate is %@",predicate);
                                        totalArr = [completeArray filteredArrayUsingPredicate:predicate];
                                        [self filterAndPopulateDataBasedonIndex];
                                        [self.tableviewObj reloadData];
                                        NSLog(@"result is %@",totalArr);


                                        I have filtered array from current date to 7 days back. I mean I am getting one week data from current date. This should work.



                                        Note: I am converting date which is coming with milli seconds by 1000, and comparing after. Let me know if you need any clarity.






                                        share|improve this answer





















                                        • In your answer completeArray is it having Array of dictionary or dataModel I want to apply on DataModel.
                                          – Sumeet Mourya
                                          Jun 14 '17 at 6:02














                                        0












                                        0








                                        0






                                        For me this is worked.



                                        NSCalendar *calendar = [NSCalendar currentCalendar];
                                        NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit ) fromDate:[NSDate date]];
                                        //create a date with these components
                                        NSDate *startDate = [calendar dateFromComponents:components];
                                        [components setMonth:0];
                                        [components setDay:0]; //reset the other components
                                        [components setYear:0]; //reset the other components
                                        NSDate *endDate = [calendar dateByAddingComponents:components toDate:startDate options:0];

                                        startDate = [NSDate date];
                                        endDate = [startDate dateByAddingTimeInterval:-(7 * 24 * 60 * 60)];//change here

                                        NSString *startTimeStamp = [[NSNumber numberWithInt:floor([endDate timeIntervalSince1970])] stringValue];
                                        NSString *endTimeStamp = [[NSNumber numberWithInt:floor([startDate timeIntervalSince1970])] stringValue];


                                        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"((paidDate1 >= %@) AND (paidDate1 < %@))",startTimeStamp,endTimeStamp];
                                        NSLog(@"predicate is %@",predicate);
                                        totalArr = [completeArray filteredArrayUsingPredicate:predicate];
                                        [self filterAndPopulateDataBasedonIndex];
                                        [self.tableviewObj reloadData];
                                        NSLog(@"result is %@",totalArr);


                                        I have filtered array from current date to 7 days back. I mean I am getting one week data from current date. This should work.



                                        Note: I am converting date which is coming with milli seconds by 1000, and comparing after. Let me know if you need any clarity.






                                        share|improve this answer












                                        For me this is worked.



                                        NSCalendar *calendar = [NSCalendar currentCalendar];
                                        NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit ) fromDate:[NSDate date]];
                                        //create a date with these components
                                        NSDate *startDate = [calendar dateFromComponents:components];
                                        [components setMonth:0];
                                        [components setDay:0]; //reset the other components
                                        [components setYear:0]; //reset the other components
                                        NSDate *endDate = [calendar dateByAddingComponents:components toDate:startDate options:0];

                                        startDate = [NSDate date];
                                        endDate = [startDate dateByAddingTimeInterval:-(7 * 24 * 60 * 60)];//change here

                                        NSString *startTimeStamp = [[NSNumber numberWithInt:floor([endDate timeIntervalSince1970])] stringValue];
                                        NSString *endTimeStamp = [[NSNumber numberWithInt:floor([startDate timeIntervalSince1970])] stringValue];


                                        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"((paidDate1 >= %@) AND (paidDate1 < %@))",startTimeStamp,endTimeStamp];
                                        NSLog(@"predicate is %@",predicate);
                                        totalArr = [completeArray filteredArrayUsingPredicate:predicate];
                                        [self filterAndPopulateDataBasedonIndex];
                                        [self.tableviewObj reloadData];
                                        NSLog(@"result is %@",totalArr);


                                        I have filtered array from current date to 7 days back. I mean I am getting one week data from current date. This should work.



                                        Note: I am converting date which is coming with milli seconds by 1000, and comparing after. Let me know if you need any clarity.







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Nov 7 '15 at 10:51









                                        Narasimha Nallamsetty

                                        646812




                                        646812












                                        • In your answer completeArray is it having Array of dictionary or dataModel I want to apply on DataModel.
                                          – Sumeet Mourya
                                          Jun 14 '17 at 6:02


















                                        • In your answer completeArray is it having Array of dictionary or dataModel I want to apply on DataModel.
                                          – Sumeet Mourya
                                          Jun 14 '17 at 6:02
















                                        In your answer completeArray is it having Array of dictionary or dataModel I want to apply on DataModel.
                                        – Sumeet Mourya
                                        Jun 14 '17 at 6:02




                                        In your answer completeArray is it having Array of dictionary or dataModel I want to apply on DataModel.
                                        – Sumeet Mourya
                                        Jun 14 '17 at 6:02


















                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.





                                        Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                        Please pay close attention to the following guidance:


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1965331%2fnspredicate-filtering-objects-by-day-of-nsdate-property%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        List item for chat from Array inside array React Native

                                        Thiostrepton

                                        Caerphilly