如何使用日期对象(到 dd-MM-yyyy HH:mm:ss)在 Swift 的 NSPredicate 中使用它

How to use Date Object (to dd-MM-yyyy HH:mm:ss) for using it in NSPredicate in Swift

我有字典的arrData,我想根据PERSON_ID、p_punchTime(string dd-MM-yyyy HH:mm:ss) 在NSPredicate[=17 中使用prevDate 和currDate 进行过滤=]

  "aarData": [
        {
          "PERSON_ID": 100000000530788,
          "p_comments": "",
          "p_person": " Amal Abutaleb",
          "p_personId": "100000000530788",
          "p_punchTime": "25-08-2020 10:32:53",
          "p_punchType": IN,
        },
        {
          "PERSON_ID": 100000000530788,
          "p_comments": "",
          "p_person": " Amal Abutaleb",
          "p_personId": "100000000530788",
          "p_punchTime": "25-08-2020 10:32:59",
          "p_punchType": OUT, 
        }
      ]

如何在 Swift.

的 NSPredicate 中使用日期 Object/string(到 dd-MM-yyyy HH:mm:ss)

当我在 NSPredicate 中传递 strCurrdate 和 strPrevdate 时有效,但过滤 returns 所有 aarData,那么 NSPredicate 中的字符串日期是否在过滤器中不起作用?

我的代码:

let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
let strCurrdate = formatter.string(from: (NHNetworkClock.shared()?.networkTime)! as Date )
let currdateObj = formatter.date(from: strCurrdate)! as NSDate    
print("currdateObj : \(currdateObj)")      //prints 2020-08-24 13:54:03 +0000 ,need dd-MM-yyyy HH:mm:ss
            
            
           
var dayComponent = DateComponents()
dayComponent.day = -1 // For removing one day (yesterday): -1
let theCalendar  = Calendar.current
let prevDate = theCalendar.date(byAdding: dayComponent, to:(NHNetworkClock.shared()?.networkTime)! as Date)
print("prevDate : \(prevDate)") 
let strPrevdate = formatter.string(from: prevDate!)  //gives string dd-MM-yyyy HH:mm:ss
let prevDateObj = formatter.date(from: strPrevdate)! as NSDate
print("prevDateObj : \(prevDateObj)")   //prints 2020-08-24 13:54:03 +0000, need dd-MM-yyyy HH:mm:ss
let resultPredicate = NSPredicate(format: "PERSON_ID CONTAINS %@ AND ( p_punchTime >= %@ AND p_punchTime <= %@)", NSString.init(format: "%@",Constants().EMPLOYEE_ID() as String),prevDateObj! as NSDate,currdateObj! as NSDate)
filteredArr = arrData.filtered(using: predicate) as NSArray 
//NOTE: aarData contains p_punchTime in format string dd-MM-yyyy HH:mm:ss

日志

(lldb) po resultPredicate
PERSON_ID CONTAINS "100000000530788" AND p_punchTime >= CAST(619860816.000000, "NSDate") AND p_punchTime <= CAST(619947216.000000, "NSDate")

我遇到了这个错误

libc++abi.dylib: terminating with uncaught exception of type NSException

这方面的任何线索

我将我的 NSPredicate 更改为字符串日期,现在工作

let resultPredicate = NSPredicate(format: "PERSON_ID == %@ AND (p_punchTime >= %@ AND p_punchTime <= %@)", NSString.init(format: "%@",Constants().EMPLOYEE_ID() as String),strPrevdate,strCurrdate )
filteredArr = arrData.filtered(using: resultPredicate) as NSArray