简体   繁体   中英

Sort array of dates ascending and starting from today date

I have an array of dates (same current year but different month and day)

I'm trying to sort the dates ascending and starting with the next date closest to today.

How to do this ?

EDIT :

I'm trying with an array containing these dates :

let a = DateComponents(calendar: Calendar.current, year: 2017, month: 6, day: 6).date
let b = DateComponents(calendar: Calendar.current, year: 2017, month: 11, day: 9).date
let c = DateComponents(calendar: Calendar.current, year: 2017, month: 12, day: 10).date
let d = DateComponents(calendar: Calendar.current, year: 2017, month: 1, day: 22).date

The date today is 2017-09-25.
The output should be in this order :

2017-11-09  //b
2017-12-10  //c
2017-01-22  //d
2017-06-06  //a

Please check :

let dateObjectsFiltered = dateObjects.filter ({ $0 > Date() })

let datesSorted = dateObjectsFiltered.sorted { return $0 < $1 }
print(datesSorted)

// DatesObj : [2017-11-08 08:00:00, 2017-10-08 08:15:00, 2017-09-08 08:15:00, 2017-10-02 08:30:00, 2017-10-02 06:30:00]
// output :   [2017-10-02 06:30:00, 2017-10-02 08:30:00, 2017-10-08 08:15:00, 2017-11-08 08:00:00]

This should work:

let dates  = [a!,b!,c!,d!]
let sorted =  dates.map{ ( ($0 < Date() ? 1 : 0), $0) }.sorted(by:<).map{$1}

I've done this before like this:

let dates: [Date] = [
  Date.distantFuture,
  Date.distantPast,
  Date().addingTimeInterval(60*60*24*1),
  Date().addingTimeInterval(60*60*24*2),
  Date().addingTimeInterval(60*60*24*3),
  Date().addingTimeInterval(-60*60*24*1),
  Date().addingTimeInterval(-60*60*24*2),
  Date().addingTimeInterval(-60*60*24*3)
]

let referenceDate = Date()
let sortedDates = dates.sorted { (left, right) -> Bool in
  return abs(left.timeIntervalSince(referenceDate)) < abs(right.timeIntervalSince(referenceDate))
}

我相信可以通过以下方式完成此工作:

dates.sorted(by: { $0.timeIntervalSinceNow < $1.timeIntervalSinceNow })
import Foundation

print("Dates:")
let dates: [Date] = [
    Date.distantFuture,
    Date.distantPast,
    Date().addingTimeInterval(60*60*24*1),
    Date().addingTimeInterval(60*60*24*2),
    Date().addingTimeInterval(60*60*24*3),
    Date().addingTimeInterval(-60*60*24*1),
    Date().addingTimeInterval(-60*60*24*2),
    Date().addingTimeInterval(-60*60*24*3)
]

dates.forEach{ print($0) }


let referenceDate = Date()

let sortedDates = dates.sorted {
    $0.timeIntervalSinceNow < $1.timeIntervalSinceNow
}

print("\r\nSorted dates:")
sortedDates.forEach{ print($0) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM