例如:
存储数据: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 { } }
我试图获得编写代码的帮助.没有错误,它不会在标签上显示任何信息.
您可以使用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 }