使用核心数据ios swift获取两个日期之间的记录

时间:2015-09-25 11:49:52

标签: ios swift filter nsdate

我试图在swift中搜索两个日期之间的记录。 我按如下所示存储日期:

     let date = NSDate()
     let dateFormatter = NSDateFormatter()
     dateFormatter.dateFormat = "yyyy'-'MM'-'dd HH':'mm':'ss"

     println(date) // prints 2015-09-26 05:22:41 +0000

     myreport.setValue(date, forKey: "date")

以下是我使用NSPredicate获取两个日期之间记录的代码:

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"

    let startDate:NSDate = dateFormatter.dateFromString(fromdate)!
    let endDate:NSDate = dateFormatter.dateFromString(todate)!

    println(fromdate) // prints 2015-09-22
    println(todate)  // prints 2015-09-29
    println(startDate) // prints 2015-09-21 20:00:00 +0000
    println(endDate)  // prints 2015-09-28 20:00:00 +0000
    let predicate1 = NSPredicate(format: "%@ >= date AND %@ <= date", argumentArray: [startDate, endDate])

    let predicate = NSCompoundPredicate(type: NSCompoundPredicateType.OrPredicateType, subpredicates: [predicate1])
    // Set the predicate on the fetch request
    request.predicate = predicate
    request.sortDescriptors = [NSSortDescriptor(key: "report_id", ascending: false)]
    var results : NSArray = context.executeFetchRequest(request, error: nil)!

注意:

1)我的fromdate和todate的格式为2015-09-25(字符串)

2)我在date属性的核心数据中的数据类型是NSDate

3)我能够成功地从核心数据中存储和获取日期

当我运行上面的代码时,我没有收到任何错误,但代码没有搜索两个日期之间的记录。我的意思是我得到空结果数组。

任何人都可以告诉我这里做错了什么。 如果需要更多信息,请告诉我。提前谢谢!

2 个答案:

答案 0 :(得分:7)

经过多次修改和测试后,这对我有用,如下所示。如果你需要如何将nsdate存储在coredata plz中,请检查上面的问题。

    println(self.appdel.fromdate) // prints 2015-09-25
    println(self.appdel.todate) // prints 2015-09-26

    var fromdate = "\(self.appdel.fromdate) 00:00" // add hours and mins to fromdate 
    var todate = "\(self.appdel.todate) 23:59" // add hours and mins to todate

    var context : NSManagedObjectContext = appdel.managedObjectContext!
    var request = NSFetchRequest(entityName: "TblReportsP")
    request.returnsObjectsAsFaults = false
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
    dateFormatter.timeZone = NSTimeZone(name: "GMT") // this line resolved me the issue of getting one day less than the selected date
    let startDate:NSDate = dateFormatter.dateFromString(fromdate)!
    let endDate:NSDate = dateFormatter.dateFromString(todate)!
    request.predicate = NSPredicate(format: "(date >= %@) AND (date <= %@)", startDate, endDate)

    request.sortDescriptors = [NSSortDescriptor(key: "report_id", ascending: false)]
    var results : NSArray = context.executeFetchRequest(request, error: nil)!

    println(results.count)

答案 1 :(得分:0)

我认为您的谓词可能有误,请尝试修改它: public

通过这种方式,您可以查看开始日期和结束日期之间的%@ <= date AND date <= %@