我难以为“最近完成”任务编写谓词,即显示任务是否在过去7天内完成。我想我需要做这样的事情:“如果现在< dateCompleted + 7天”。
dateCompleted是表上的一个属性,但是我不确定我应该如何获得它的值并在谓词中添加7天。我想在编写NSPredicate之前我需要先获取属性值,但是怎么样?此时我无法访问managedObject。
这可能接近解决方案,但我无法弄清楚如何定义'oneWeek',我认为你不能在定义谓词时添加值:
NSPredicate *pred = [NSPredicate predicateWithFormat:@"%@ < todoCompletedDate + %@", [NSDate date], oneWeek];
答案 0 :(得分:18)
你快到了。
首先,您需要定义日期范围。要做到这一点,你需要从今天的日期开始,然后添加几周的时间来找到有效范围的结束。获得该范围后,您可以构建谓词以查找截止日期&gt; = start和&lt; = end的所有任务。这是我编写的一些非常相似的代码的摘录......
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];
答案 1 :(得分:0)
从今天的数据开始前一周。快速代码
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)
在我的情况下,我的核心数据库中有post的时间戳值,所以我也使用下面的函数来获取时间戳值
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
}
答案 2 :(得分:-1)
要获得当天的开始,您可以使用:
NSDate *date = [NSDate date];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *dateComponents = [gregorianCalendar components:(NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear) fromDate:date];
NSDate *startDate = [gregorianCalendar dateFromComponents:dateComponents];
并获得结束日期:
NSCalendar* gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents* dateComponents = [gregorianCalendar components:(NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear) fromDate:date];
[dateComponents setHour:23];
[dateComponents setMinute:59];
[dateComponents setSecond:59];
[dateComponents setDay:[dateComponents day]+7];
NSDate *endDate = [gregorianCalendar dateFromComponents:dateComponents];