Search code examples
iossortingnestednsarray

Nested Sorting NSArray


I have this NSArray of NSDates, that I want sort in such a way, that the dates are descending, but the hours are ascending.

the sorted array would (paraphrased) look like:

{tomorrowMorning, tomorrowAfternoon, thisMorning, thisAfternoon, yesterdayMorning, yesterdayAfternoon}

What would be the best approach to accomplish this.


Solution

  • Add an extension to Date -

    extension Date {
    
        public func dateWithZeroedTimeComponents() -> Date? {
    
            let calendar = Calendar.current
    
            var components = calendar.dateComponents([.year, .month, .day], from: self)
            components.hour = 0
            components.minute = 0
            components.second = 0
    
            return calendar.date(from: components)
        }
    }
    

    Then use this sort code -

    // example test data
    let dates: [Date] = [Date(timeIntervalSinceNow: -80060), Date(timeIntervalSinceNow: -30), Date(timeIntervalSinceNow: -75000), Date(timeIntervalSinceNow: -30000), Date(timeIntervalSinceNow: -30060)]
    
    let sortedDates = dates.sorted { (date1, date2) -> Bool in
    
        if let date1Zeroed = date1.dateWithZeroedTimeComponents(), let date2Zeroed = date2.dateWithZeroedTimeComponents() {
    
            // if same date, order by time ascending
            if date1Zeroed.compare(date2Zeroed) == .orderedSame {
                return date1.compare(date2) == .orderedAscending
            }
            // otherwise order by date descending
            return date1.compare(date2) == .orderedDescending
        }
    
        return true
    }
    
    print(sortedDates)
    

    Result - [2017-06-15 05:20:29 +0000, 2017-06-15 05:21:29 +0000, 2017-06-15 13:40:59 +0000, 2017-06-14 15:27:09 +0000, 2017-06-14 16:51:29 +0000]

    I think this is what you want?