您不能简单地使用您的日期与今天的日期进行比较:
原文链接:https://www.f2er.com/swift/319028.htmllet today = Date() let datePredicate = NSPredicate(format: "%K == %@",#keyPath(ModelType.date),today)@H_502_1@它不会显示任何内容,因为您的日期不太可能是完全比较日期(它还包括秒和毫秒) @H_502_1@解决方案是这样的:
// Get the current calendar with local time zone var calendar = Calendar.current calendar.timeZone = NSTimeZone.local // Get today's beginning & end let dateFrom = calendar.startOfDay(for: Date()) // eg. 2016-10-10 00:00:00 let dateTo = calendar.date(byAdding: .day,value: 1,to: dateFrom) // Note: Times are printed in UTC. Depending on where you live it won't print 00:00:00 but it will work with UTC times which can be converted to local time // Set predicate as date being today's date let fromPredicate = NSPredicate(format: "%@ >= %@",date as NSDate,dateFrom as NSDate) let toPredicate = NSPredicate(format: "%@ < %@",dateTo as NSDate) let datePredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [fromPredicate,toPredicate]) fetchRequest.predicate = datePredicate@H_502_1@这是迄今为止最简单的&只显示具有今天日期的对象的最短方式.