Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data- predicate with dates

I'm stumped trying to write a predicate for "Recently Completed" tasks, i.e. show the task if it was completed within the last 7 days. I think I need to do something like this: "if NOW < dateCompleted + 7 days".

The dateCompleted is an attribute on the table, but I'm not sure how I'm supposed to get it's value and add 7 days to it from within the predicate. I guess I need to fetch the attribute value first before writing the NSPredicate, but how? I don't have access to the managedObject at this point.

This might be close the solution, but I can't figure out how to define 'oneWeek' and I don't think you can just add values when defining the predicate:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"%@ < todoCompletedDate + %@", [NSDate date], oneWeek];
like image 213
Z S Avatar asked Jul 25 '11 07:07

Z S


2 Answers

You're almost there.

Firstly you need to define your date range. To do that you'll want to start with today's date and then add a weeks worth of days to find the end of the valid range. Once you have that range you can build your predicate to find all tasks with a due date >= start and <= end. Here's an extract from some code I've written to do something very similar...

NSDate *today = [NSDate date];
NSDate *startOfToday = [DateHelper startOfDay:today];
NSDate *endOfWeek = [DateHelper addDaysToDate:today daysToAdd:6];
return [NSPredicate predicateWithFormat:@"(dueDate >= %@) AND (dueDate <= %@) AND complete == 0", startOfToday, endOfWeek];
like image 113
mmccomb Avatar answered Nov 05 '22 06:11

mmccomb


To get one week before data from today. swift code

let calendar = NSCalendar.currentCalendar()
let now = NSDate()
let nowTimeStamp = self.getCurrentTimeStampWOMiliseconds(now)

let sevenDaysAgo = calendar.dateByAddingUnit(.Day, value: -7, toDate: now, options: [])!
let startDate = calendar.startOfDayForDate(sevenDaysAgo)
let startDateTimeStamp = self.getCurrentTimeStampWOMiliseconds(startDate)

let predicate1 = NSPredicate(format:"(iCreatedAt >= %@) AND (iCreatedAt < %@) AND location = %@", startDateTimeStamp, nowTimeStamp)

In my case i have timestamp value of post in my coreData DB so i use below function also to get timestamp value

 func getCurrentTimeStampWOMiliseconds(dateToConvert: NSDate) -> String {
        let objDateformat: NSDateFormatter = NSDateFormatter()
        objDateformat.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let strTime: String = objDateformat.stringFromDate(dateToConvert)
        let objUTCDate: NSDate = objDateformat.dateFromString(strTime)!
        let milliseconds: Int64 = Int64(objUTCDate.timeIntervalSince1970)
        let strTimeStamp: String = "\(milliseconds)"
        return strTimeStamp
    }
like image 30
Hardik Thakkar Avatar answered Nov 05 '22 06:11

Hardik Thakkar