user3722523 user3722523 - 24 days ago 11
Swift Question

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

Answer Source

This should work:

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