使用NSPredicate过滤fetchRequest年/月

时间:2017-02-22 08:56:03

标签: ios swift3 nsdate nspredicate nsfetchrequest

我有一个应用程序,它有几个时间条目,日期保存为NSDate。

我想使用获取请求来过滤我从其他地方获得的特定年份和月份。如何使用NSPredicate过滤一年和一月?

let predicate = NSPredicate(format: "%K == %D && %K == %D", ???, selectedMonth, ???, selectedYear)

更新

使用帮助Raki指出我提出了以下代码:

var dateComp = DateComponents()
dateComp.year = Int(selectedYear)
dateComp.month = Int(selectedMonth)
dateComp.day = 1

let calendar = Calendar.current
let firstDayOfTheMonth = calendar.date(from: dateComp)

var oneMonth = DateComponents()
oneMonth.month = 1
let beginningOfNextMonth = calendar.date(byAdding: oneMonth, to: firstDayOfTheMonth!)

谓词:

let predicate = NSPredicate(format: "date >= %@ AND date < %@", firstDayOfTheMonth as! CVarArg, beginningOfNextMonth as! CVarArg)

我收到一封带有以下消息的SIGABRT:

Could not cast value of type 'Foundation.Date' (0x1073a0ae0) to 'Swift.CVarArg' (0x1196851c8).

Xcode建议我添加“as!CVarArg”

更新2

以下谓词现在有效:

let predicate = NSPredicate(format: "%K >= %@ && %K < %@", "date", firstDayOfTheMonth! as NSDate, "date", beginningOfNextMonth! as NSDate)

1 个答案:

答案 0 :(得分:1)

你不能这样断言,但是你可以从月份和年份开始创建两个Dates,从月份的开始日期和月份的结束日期开始。

现在你需要像这样简单地谓词。

let predicate = NSPredicate(format: "%K >= %@ && %K <= %@", "DateAttribute", startDateOfMonth as NSDate, "DateAttribute", endDateOfMonth as NSDate)

修改:如果您不知道如何为startDateOfMonthendDateOfMonth创建日期,则可以使用DateComponents创建日期。< / p>

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!)