仅按日期时间/日期选择器中的日期快速过滤 [英] Filter by date only from datetime/datepicker in swift
问题描述
我在表单中使用日期时间选择器,并将以下数据插入到核心数据实体(属性)
I am using datetime picker in form and inserting data as follows to core data entity (attribute)
`appointment.date = appointmentDate.date //it is getting date as well and time
appointment.title = "Appointment"
do {
try managedObjectContext.save()`
,并且在另一个viewcontroller中,我这样做是根据日期来过滤记录.我有一个返回日期的日历.
and in another viewcontroller i am doing this to filter records based on date. I have a calendar which returns date.
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Appointment")
let sortDescriptor = NSSortDescriptor(key: "date", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
let predicate = NSPredicate(format: "date = %@", calendar.selectedDate! as NSDate)
fetchRequest.predicate = predicate
尝试按日期过滤(忽略时间),但不起作用(不显示任何内容).如果删除谓词,则显示所有记录.
Trying to filter just by the date (ignoring time) but it is not working(does not show anything).If I remove the predicate all records are displayed.
正确的方法是什么?我在哪里做错了?是格式问题吗?
What is the right way or where am i doing it wrong? Is it a format problem?
推荐答案
如果要过滤所选日中的记录,则必须应用带有开始日期和结束日期的谓词>
If you want to filter the records which are in the selected day you have to apply a predicate with start and end date
let startDate = Calendar.current.startOfDay(for: calendar.selectedDate)
let endDate = Calendar.current.date(byAdding: .day, value: 1, to: startDate)
let predicate = NSPredicate(format: "date >= %@ AND date < %@", startDate as NSDate, endDate as NSDate)
这篇关于仅按日期时间/日期选择器中的日期快速过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!