Skip to content

Instantly share code, notes, and snippets.

@hacknicity
Created March 15, 2023 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hacknicity/274dde42f296f095a011b3d399a5ffc1 to your computer and use it in GitHub Desktop.
Save hacknicity/274dde42f296f095a011b3d399a5ffc1 to your computer and use it in GitHub Desktop.
Swift code for finding first future date from an array
// We only want to calculate this once
let now = Date.now
// Create some test data
let allMatches: [Date] = (0...10)
.map { _ in
let randomNumberOfDays = (-1000...1000).randomElement()!
return Calendar.current.date(byAdding: .day, value: randomNumberOfDays, to: now)!
}
print("now: \(now)\n")
print(allMatches.sorted().map { "match: \($0)" }.joined(separator: "\n"))
print()
// Calculate nearest future date from now
let matchDate = allMatches
.filter { $0.timeIntervalSince(now) > 0 }
.min()
if let matchDate {
print("matchDate: \(matchDate)")
} else {
print("no dates are in the future")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment