核心数据谓词按今天的日期过滤

核心数据谓词按今天的日期过滤,第1张

核心数据谓词按今天的日期过滤

您不能简单地将您的日期与今天的日期进行比较:

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

到目前为止,这是仅显示具有当前日期的对象的最简单,最短的方法。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5666542.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存