2017-06-15 169 views
0

我有NSArray的NSDates,我想以這種方式排序,日期是降序,但小時正在上升。嵌套排序NSArray

數組排序會(意譯)的樣子:

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

什麼是完成這一任務的最佳方法。

+0

只要編寫一個排序比較,如果日期不同,就排序日期,如果兩個日期相同,則按時間排序。 – Paulw11

+0

@ Paulw11嗯,是的,我明白了。但我無法弄清楚如何做到這一點。 – Sjakelien

+0

試試這個https://stackoverflow.com/questions/38168594/sort-objects-in-array-by-date –

回答

0

添加擴展日期 -

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) 
    } 
} 

然後使用這種代碼 -

// 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) 

結果 - [2017年6月15日五點二十分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]

我認爲這是你想要的?

+0

是的,謝謝。我需要在Obj-c中這樣做,但這對我來說很有意義。 – Sjakelien