0

I have an array of dates and i want to keep the nearest future day from today.

Is there any function to make it easier than comparing each date in a bucle?

I have this code:

var nearestDate: Date?

for match in allMatches {

      let actualDate = Date()

      let dateFormatter = DateFormatter()
      dateFormatter.timeZone = TimeZone(abbreviation: "GMT+00:00")
      dateFormatter.dateFormat = "dd'-'MM'-'yyyy"
                        
      let matchDate = dateFormatter.date(from: match.date ?? "")
      nearestDate = dateFormatter.date(from: "01-01-2200")

      if let matchDate = matchDate {
            if !matchDate.isInPast {
                  if matchDate < nearestDate! {
                        nearestDate = matchDate
                  }
            }
      }
}
print(nearestDate)

But its not even returning the correct day

  • This question was closed as a duplicate before I could add my answer. The other answer is less efficient than mine and repeatedly calculates the time now (resulting in a tiny amount of drift). My answer, with test data, is here: https://gist.github.com/hacknicity/274dde42f296f095a011b3d399a5ffc1 – Geoff Hackworth Mar 15 '23 at 14:02

0 Answers0