Swift coreData – 格式化date并在谓词中使用它
H.我有一个名为Agendadate的实体,一个名为AgendaEvent。 议程事件与议程日程(议程date)有许多关系。
在我的AgendaDate我有一个对象date(typesdate)。
我使用这样的谓词:
fetchRequest.predicate = NSPredicate(format: "ANY agendaDates.dates == %@", date as CVarArg)
我想格式化date有这样的:
“dd MM yyyy”而不是“yyyy MM dd hh:mm:ss”
我需要在谓词中比较两个date,但没有时间? 可能吗?
更新—–这是我的function更新,因为你已经build议:
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 }
这里是应该configuration单元格的function,并只select具有相同date的事件:
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 } } } }
不要为此使用自定义的string格式。 您想要获取所有与具有与指定date同一天的date的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)
它为所有相关对象testing$a.dates >= startDate AND $a.dates < endDate
,如果至less有一个条件匹配,则返回true。