-1

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
user3722523
  • 1,740
  • 2
  • 15
  • 27

5 Answers5

1

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]
Vini App
  • 7,339
  • 2
  • 26
  • 43
1

This should work:

let dates  = [a!,b!,c!,d!]
let sorted =  dates.map{ ( ($0 < Date() ? 1 : 0), $0) }.sorted(by:<).map{$1}
Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

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))
}
mm282
  • 453
  • 3
  • 7
0

I believe something like the following will do the job:

dates.sorted(by: { $0.timeIntervalSinceNow < $1.timeIntervalSinceNow })
sCha
  • 1,454
  • 1
  • 12
  • 22
0
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) }
Alexander
  • 59,041
  • 12
  • 98
  • 151