核心数据谓词过滤器按今天的日期 [英] Core Data Predicate Filter By Today's Date

查看:26
本文介绍了核心数据谓词过滤器按今天的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Swift 中通过 Date 属性过滤核心数据托管对象?

How can I filter Core Data Managed Objects by their Date attribute in Swift?

目标是按今天的日期过滤获取的对象.

The goal is to filter fetched objects by today's date.

推荐答案

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

You can't simply use to compare your date to today's date:

let today = Date()
let datePredicate = NSPredicate(format: "%K == %@", #keyPath(ModelType.date), today)

它不会显示任何内容,因为您的日期不太可能是确切的比较日期(它也包括秒和毫秒)

It will show you nothing since it's unlikely that your date is the EXACT comparison date (it includes seconds & milliseconds too)

解决办法是:

// 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: "%@ >= %K", dateFrom as NSDate, #keyPath(ModelType.date))
let toPredicate = NSPredicate(format: "%K < %@", #keyPath(ModelType.date), dateTo as NSDate)
let datePredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [fromPredicate, toPredicate])
fetchRequest.predicate = datePredicate

这是迄今为止最简单的 &仅显示具有今天日期的对象的最短方法.

It's by far the easiest & shortest way of showing only objects which have today's date.

这篇关于核心数据谓词过滤器按今天的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆