Swift coreData: formatee la fecha y úsela en predicado
H. Tengo una entidad llamada Agendadate y una llamada AgendaEvent. AgendaEvent tiene una relación de muchos a muchos con AgendaDate (agendaDates).
en mi AgendaDate tengo un objeto fechas (de tipo Fecha).
Estoy usando un predicado así:
fetchRequest.predicate = NSPredicate(format: "ANY agendaDates.dates == %@", date as CVarArg)
Estoy tratando de formatear fechas para tener esto:
"dd MM aaaa" en lugar de "aaaa MM dd hh: mm: ss"
¿Necesito comparar en el predicado dos fechas pero sin el tiempo? ¿Es posible?
ACTUALIZACIÓN ----- Aquí está mi función actualizada como usted ha sugerido:
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
}
y aquí está la función que debe configurar la celda y tomar solo los eventos que tienen la misma fecha de la fecha seleccionada:
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
}
}
}
}