Hello, I have an array of dates and I'm trying to filter it to get, in three different array today dates - future dates - past dates.
// Appointment is a CoreData entity with a property date: Date
@Published var scheduledAppointments: [Appointment] = [] // this array should contain future appointments from 00:00 of tomorrow and later.
@Published var pastAppointments: [Appointment] = [] // this array should contain past appointments from 23:59 of yesterday and before.
@Published var todayAppointments: [Appointment] = [] // this array should contain today appointments from 00:00 to 23:59.
I've tried a lot of solutions (many of which didn't work) and I end up with this solution but i think is weird.
func getTodayAppointments() {
let allAppointments = pet.appointments?.allObjects as? [Appointment] ?? []
let today = allAppointments.filter { appointment in
let appointmentComponents = Calendar.current.dateComponents([.day, .year, .month], from: appointment.appointmentDate)
let todayComponents = Calendar.current.dateComponents([.day, .year, .month], from: Date())
return appointmentComponents == todayComponents
}
todayAppointments = today.sorted {
$0.appointmentDate > $1.appointmentDate
}
}
func getScheduledAppointments() {
let allAppointments = pet.appointments?.allObjects as? [Appointment] ?? []
let scheduled = allAppointments.filter { appointment in
let todaySeconds = getTodaySeconds()
return appointment.appointmentDate >= Date.now.addingTimeInterval(Double(86400 - todaySeconds - 1))
}
scheduledAppointments = scheduled.sorted {
$0.appointmentDate > $1.appointmentDate
}
}
func getPastAppointments() {
let allAppointments = pet.appointments?.allObjects as? [Appointment] ?? []
let past = allAppointments.filter { appointment in
let todaySeconds = getTodaySeconds()
return appointment.appointmentDate <= Date.now.addingTimeInterval(Double(-todaySeconds - 1))
}
pastAppointments = past.sorted {
$0.appointmentDate > $1.appointmentDate
}
}
// With this function I get the seconds passed today and then subtract or add this value to .addingTimeInterval otherwise some appointments were not displayed or displayed in more than 1 array.
func getTodaySeconds() -> Int {
let today = Calendar.current.dateComponents([.hour, .minute, .second], from: Date())
let minuteInSeconds = (today.minute ?? 0) * 60
let hourInSeconds = (today.hour ?? 0) * 3600
let seconds = today.second ?? 0
return minuteInSeconds + hourInSeconds + seconds
}
Here the result on a list
Can you suggest improvements to this code?
Thank you! ( English is not my main language, I hope you understand )