Created
March 15, 2023 14:01
-
-
Save hacknicity/274dde42f296f095a011b3d399a5ffc1 to your computer and use it in GitHub Desktop.
Swift code for finding first future date from an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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