如何查找存储数据的最近日期

时间:2016-01-11 16:40:47

标签: swift date time nsdate

例如:

  • 存储数据:date = data1(2015.12.31),data2(2016.01.05),data3(2016.01.14),data4(2016.01.15),data5(2016.01.18)
  • 今天是2016.01.12
  • 那么最近的数据是 data3

这里可以调用哪些方法data3?

核心数据中的

realDate(datePicker.date), date(textField.text), content(textField.text)

var stores: Contact!
// Contact is CoreData Entity Name.
@IBOutlet weak var label: UILabel!

ViewController viewDidLoad:

let list = [stores]
let timeSort = list.map{_ in stores?.realDate!.timeIntervalSinceNow}.filter{$0 > 0}.sort(<)
  if let firstTime = timeSort.first {
  _ = NSDate(timeIntervalSinceReferenceDate: firstTime!)
    if timeSort.first != nil {
      label.text = stores?.content
    } else { }
  }

我试图获得编写代码的帮助。没有错误,它不会在标签上显示任何信息。

1 个答案:

答案 0 :(得分:6)

您可以使用NSDate属性timeIntervalSinceNow对日期进行排序并获得第一个正值:

编辑/更新:

Swift 3 引入符合Date协议的Comparable,因此现在可以轻松排序:

extension Date {
    init?(_ year: Int,_ month: Int,_ day: Int) {
        guard let date = DateComponents(calendar: .current, year: year, month: month, day: day, hour: 12).date else { return nil }
        self = date
    }
}

游乐场测试:

let dateList = [Date(2018, 2, 18)!, Date(2017, 12, 31)!, Date(2018, 1, 5)!, Date(2018, 2, 14)!, Date(2018, 2, 15)!]

if let closestDate = dateList.sorted().first(where: {$0.timeIntervalSinceNow > 0}) { // "Feb 15, 2018, 12:00 PM"
    print(closestDate.description(with: .current)) // Thursday, February 15, 2018 at 12:00:00 PM Brasilia Summer Time
}