您不能简单地将您的日期与今天的日期进行比较:
let today = Date()let datePredicate = NSPredicate(format: "%K == %@", #keyPath(ModelType.date), today)
它不会显示任何内容,因为您的日期不太可能是精确的比较日期(也包括秒和毫秒)
解决方法是这样的:
// Get the current calendar with local time zonevar calendar = Calendar.currentcalendar.timeZone = NSTimeZone.local// Get today's beginning & endlet dateFrom = calendar.startOfDay(for: Date()) // eg. 2016-10-10 00:00:00let 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 datelet fromPredicate = NSPredicate(format: "%@ >= %@", date as NSDate, dateFrom as NSDate)let toPredicate = NSPredicate(format: "%@ < %@", date as NSDate, dateTo as NSDate)let datePredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [fromPredicate, toPredicate])fetchRequest.predicate = datePredicate
到目前为止,这是仅显示具有当前日期的对象的最简单,最短的方法。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)