小时。 我有一个名为Agendadate的实体和一个名为AgendaEvent的实体。 AgendaEvent与AgendaDate(agendaDates)存在多种关系。
在我的AgendaDate中,我有一个对象日期(日期类型)。
我正在使用这样的谓词:
fetchRequest.predicate = NSPredicate(format: "ANY agendaDates.dates == %@", date as CVarArg)
我试图将日期格式设置为:
" dd MM yyyy"而不是" yyyy MM dd hh:mm:ss"
我需要在谓词中比较两个日期但没有时间吗? 有可能吗?
UPDATE ----- 根据您的建议,我的功能已更新:
func agendaEventsWithDate(date: Date) -> NSFetchRequest<AgendaEvent>
{
// create a fetch request that will retrieve all the AgendaEvents.
let fetchRequest = NSFetchRequest<AgendaEvent>(entityName: "AgendaEvent")
// set the predicate to only keep AgendaEvents where the related AgendaDate's date matches the passed in date.
let cal = Calendar.current
let startOfDay = cal.startOfDay(for: eventDate)
let endOfDay = cal.date(byAdding: .day, value: 1, to: startOfDay)!
print(startOfDay)
print(endOfDay)
// fetchRequest.predicate = NSPredicate(format: "ANY agendaDates.agendaDates == %@", date as CVarArg)
fetchRequest.predicate = NSPredicate(format: "SUBQUERY(agendaDates, $a, $a.dates >= %@ AND $a.dates < %@).@count > 0",
startOfDay as NSDate, endOfDay as NSDate)
return fetchRequest
}
以及这里应该配置单元格的函数,并且只接受与所选日期具有相同日期的事件:
func configuringCell(cell: CalendarAgendaCell, indexPath: IndexPath) {
for dates in calendar.selectedDates {
for dateOfEvent in myEventDate {
formatter.dateFormat = "dd MM yyyy"
let dateToCompare = formatter.string(from: dates)
formatter.dateFormat = "dd-MM-yyyy"
let comparingDate = formatter.date(from: dateToCompare)!
if dateOfEvent == dateToCompare {
myTempEvents = try! context.fetch(agendaEventsWithDate(date: comparingDate))
let myEvent = myTempEvents[indexPath.row]
cell.configureCell(agendaEvent: myEvent)
} else {
// the array is empty
}
}
}
}
答案 0 :(得分:0)
不要为此目的使用自定义字符串格式。你想要获取 与具有日期的Agendadate对象相关的所有条目 在同一天的同一天。
因此,您首先计算当天的开始和结束时间:
let date = Date()
let cal = Calendar.current
let startOfDay = cal.startOfDay(for: date)
let endOfDay = cal.date(byAdding: .day, value: 1, to: startOfDay)!
然后使用此SUBQUERY:
let predicate = NSPredicate(format: "SUBQUERY(agendaDates, $a, $a.dates >= %@ AND $a.dates < %@).@count > 0",
startOfDay as NSDate, endOfDay as NSDate)
它为所有人测试$a.dates >= startDate AND $a.dates < endDate
相关对象,如果至少有一个匹配则产生true
条件。