Filter fetchRequest for year/month using NSPredicate
You cannot predicate like this, but you can create two Dates
from your month and year which start day of month and end day of month.
Now you need to simply predicate like this way.
let predicate = NSPredicate(format: "%K >= %@ && %K <= %@", "DateAttribute", startDateOfMonth as NSDate, "DateAttribute", endDateOfMonth as NSDate)
Edit: If you don't know how to create date for startDateOfMonth
and endDateOfMonth
, then you can create it using DateComponents
.
let selectedMonth = 11
let selectedYear = 2015
var components = DateComponents()
components.month = selectedMonth
components.year = selectedYear
let startDateOfMonth = Calendar.current.date(from: components)
//Now create endDateOfMonth using startDateOfMonth
components.year = 0
components.month = 1
components.day = -1
let endDateOfMonth = Calendar.current.date(byAdding: components, to: startDate!)
NSPredicate with NSDate filtering by day/month but not year
First, to extract a day and month from a date...
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
NSInteger day = [components day];
NSInteger month = [components month];
Next, (one way) to build a predicate...
[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary * bindings) {
// object must be cast to the type of object in the list
MyObject *myObject = (MyObject *)object;
NSDate *creationDate = myObject.creationDate;
// do whatever you want here, but this block must return a BOOL
}];
Putting those ideas together...
- (NSPredicate *)predicateMatchingYearAndMonthInDate:(NSDate *)date {
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
NSInteger day = [components day];
NSInteger month = [components month];
return [NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary * bindings) {
MyObject *myObject = (MyObject *)object;
NSDate *creationDate = myObject.creationDate;
NSDateComponents *creationComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:creationDate];
NSInteger creationDay = [creationComponents day];
NSInteger creationMonth = [creationComponents month];
return day == creationDay && month == creationMonth;
}];
}
That's it. Build the predicate with some NSDate
who's day and month you want to match in the array, then run that predicate on the array (filteredArrayUsingPredicate:
).
NSDate *today = [NSDate date];
NSPredicate *predicate = [self predicateMatchingYearAndMonthInDate:today];
NSArray *objectsCreatedToday = [myArray filteredArrayUsingPredicate:predicate];
NSPredicate: filtering objects by day of NSDate property
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];
coredata filtering by date using NSPredicate returns nothing
date
is actually a timestamp, so doing ==
with it will only return items which have that exact timestamp.
To get all the entries on a specific date you'll want to get the NSDate
for the start of the day (startOfDay
), and the NSDate
for the end of the day (endOfDay
) then modify the predicate to get dates between those two values using:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"dates >= %@ AND dates >= %@", startOfDay, endOfDay];
To calculate the startOfDay
and endOfDay
you can either do it yourself manually or there are some other libraries you can use to calculate it such as https://github.com/erica/NSDate-Extensions.
CoreData: NSPredicate filter by date
In your model you set the dateTime
property as a Date
object, but you saved it as a double
.
So you have to do:
dateTime = NSDate(dateWithTimeIntervalSinceReferenceDate:Double(activityInfo["eventDateTime"] as! String))
Note, I don't speak Swift, so I don't know if this code could be shorter, but you get the idea.
how to build a NSPredicate filtering all days in a month using NSDate?
Yes. You need to figure out what the first instant of the month is, as well as the first instant of the next month. Here's how I would do it:
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *nowComponents = [calendar components:NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:now];
[nowComponents setDay:1];
NSDate *beginningOfCurrentMonth = [calendar dateFromComponents:nowComponents];
NSDateComponents *oneMonth = [[NSDateComponents alloc] init];
[oneMonth setMonth:1];
NSDate *beginningOfNextMonth = [calendar dateByAddingComponents:oneMonth toDate:beginningOfCurrentMonth options:0];
Once you've got those two NSDate
s, then you can do:
[NSPredicate predicateWithFormat:@"date >= %@ AND date < %@", beginningOfCurrentMonth, beginningOfNextMonth];
Core Data NSPredicate - Match Dates
First of all the exception occurs because the placeholder %@
is wrong. %@
is for objects, a Double
value is represented by %f
.
Second of all if you want to fetch all dates which are in a specific day you have to create a date range (0:00–23:59) of that day.
Using Calendar
you get 0:00 with startOfDay(for:)
and the end of the day by adding a day
and the <
operator.
For example
let calendar = Calendar.current
let startDate = calendar.startOfDay(for: selectedDate)
let endDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
let predicate = NSPredicate(format: "date >= %@ AND date < %@", argumentArray: [startDate, endDate]))
Related Topics
iOS Facebook Login "Given Url Is Not Allowed by the Application Configuration"
Setting a Rotation Point for Cgaffinetransformmakerotation Swift
How to Detect Tap on Clear Part of Uitableview
Using Two Versions of a Cocoapod Dependency
Animating Calayer's Shadowpath Property
Mask Uiview with Uibezierpath - Stroke Only
Replace iOS App Emoji with Twitter Open Source Twemoji
[Nsthread Ismainthread]' Always Returns Yes
Table View Didselectrowatindexpath, Only Works After Selecting Second Click
Avplayer with Playback Controls of Avplayerviewcontroller
Drawing a Polygon with One Color for Stroke, and a Different One for Fill
How to Access Extension of Uicolor in Swift
Remove Uiwebview's Internal Cache
Undefined Symbols for Architecture Arm64 "_Objc_Class_$_Sfsafariviewcontroller"
iOS Ibeacon: How to Get All of Proximityuuid Programmatically