I have an array
of Person
. The Person object has many fields between them inscriptionDate
(a timestamp
). I have to create a collectionView
from this array
but using sections
. Every section has a header that is inscriptionDate
as a date having this format dd/mm/yyyy
. I have to sort the array
by inscriptionDate
but without time (only the format dd/mm/yyyy
) in order to load the data in the collectionView
(taking into consideration the sections). I have found from another question this solution. But how can I sort the array
before doing this? How can I use this:
order = NSCalendar.currentCalendar().compareDate(now, toDate: olderDate,
toUnitGranularity: .Day)
in my case?
First, you'll need to clean timestamp before the sorting. You can do that by using Calendar
and Date
extension:
extension Date {
func noTime() -> Date! {
let components = Calendar.current.dateComponents([.day, .month, .year], from: self)
return Calendar.current.date(from: components)
}
}
Then you'll just need to sort your array by date without time:
let sortedByDate = persons.sorted { $0.inscriptionDate.noTime() < $1.inscriptionDate.noTime() }
Note. Be careful with compareDate
function of Calendar
, since it comparing only specific component. If in this example: NSCalendar.currentCalendar().compareDate(now, toDate: olderDate, toUnitGranularity: .Day)
you'll have same days in different months, the comparing result will show that dates are equal.