Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the nearest date of the stored data

For example:

  • stored data: date = data1(2015.12.31), data2(2016.01.05), data3(2016.01.14), data4(2016.01.15), data5(2016.01.18)
  • today is 2016.01.12
  • then nearest data is data3

What are the methods that can be called here data3?

realDate(datePicker.date), date(textField.text), content(textField.text) in Core Data.

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

I was trying to get help for writing code. There is no error, it does not display any information on the label.

like image 533
Iden Lim Avatar asked Jan 11 '16 16:01

Iden Lim


People also ask

How do I find the nearest date in Excel?

Finding the future closest date to today in ExcelSelect the blank cell B2, copy and paste formula =MIN(IF(A2:A18>TODAY(),A2:A18)) into the Formula Bar, and then press Ctrl + Shift + Enter keys simultaneously. See screenshot: Then you will get the future closest date to today in cell B2.


1 Answers

You can use NSDate property timeIntervalSinceNow to sort your dates and get the first positive value:

edit/update:

Swift 3 introduced Date which conforms to Comparable protocol so it can be easily sorted now:

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

Playground testing:

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
}
like image 52
Leo Dabus Avatar answered Nov 09 '22 21:11

Leo Dabus