Search This Blog

Wednesday, November 23, 2016

How to find nearest(closest) date to today

If we have array of dates and we need to find what date is neasrest to today date. There is special method in iOS SDK API - timeIntervalSince
public func timeIntervalSince(_ date: Date) -> TimeInterval

This method will return double value - time interval between two dates - self date object and parameter date. Also this time interval can be positive or negative. So for getting nearest date we need to get absolute positive value of time interval. For that purpose we will use method fabs
public func fabs(_: Double) -> Double

Algorithm - How to define nearest date to today
func findNearestDateToToday(datesArray: [Date]) -> Date {
        let today = Date()
        let firstDate = datesArray[0]
        var min = fabs(today.timeIntervalSince(firstDate))
        var minIndex = 0
        for i in 1..<datesArray.count {
            let currentDate = datesArray[i]
            let currentMin = fabs(today.timeIntervalSince(currentDate))
            if currentMin < min {
                min = currentMin
                minIndex = i
            }
        }
        return datesArray[minIndex]
}

7 comments:

  1. Really amazing information you have shared i was looking for this kind of unique information please do share that kind of unique information more as you can.
    -Web Development Services

    ReplyDelete
  2. After a long time i found a unique and on purpose information about Custom Designed Websites. Can't wait to have more from you.

    ReplyDelete
  3. Thank you for writing this blog and giving this vital and useful information. Best Custom Websites

    ReplyDelete
  4. Thank you very much for drawing my notice to this. Your blog is jam-packed with useful facts. Until I read that, I would have no idea. I'll come back for more fantastic material.
    Best wishes, and good luck.
    Web Design USA

    ReplyDelete
  5. Good content. I was looking for this type of content. Saved my time for further search.
    You should always provide that type of content. I appreciate your determination to give the students a good title.Custom Designed Websites

    ReplyDelete
  6. Great share!One of the best blogs I have Ever Seen. Keep going!
    QA Testing Services

    ReplyDelete
  7. Excellent website. This is the first time I've visited this blog, and it's fantastic. The main thing is that the content in this blog is written in a clear and intelligible manner.
    SEO Agency

    ReplyDelete