您不能简单地使用您的日期与今天的日期进行比较:
let today = Date() let datePredicate = nspredicate(format: "%K == %@",#keyPath(ModelType.date),today)
它不会显示任何内容,因为您的日期不太可能是完全比较日期(它还包括秒和毫秒)
解决方案是这样的:
// 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
这是迄今为止最简单的&只显示具有今天日期的对象的最短方式.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。