从今天起按日期升序排列日期

时间:2017-09-25 15:14:41

标签: ios swift xcode date swift4

我有一系列日期(当前年份相同但月份和日期不同)

我正在尝试对日期提升进行排序,并从距离今天最近的下一个日期开始。

怎么做?

编辑:

我正在尝试使用包含这些日期的数组:

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

今天的日期是2017-09-25 输出应按此顺序排列:

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

5 个答案:

答案 0 :(得分:1)

请检查:

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]

答案 1 :(得分:1)

这应该有效:

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

答案 2 :(得分:0)

我之前就这样做了:

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

答案 3 :(得分:0)

我相信以下内容可以完成这项工作:

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

答案 4 :(得分: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) }