I want to find the date of every Sundays in the last 50 years using Swift. I thought the 'enumerateDates' (instance method of Calendar) might help. But I couldn't figure out how to use it.
func enumerateDates(startingAfter: Date, matching: DateComponents, matchingPolicy: Calendar.MatchingPolicy, repeatedTimePolicy: Calendar.RepeatedTimePolicy, direction: Calendar.SearchDirection, using: (Date?, Bool, inout Bool) -> Void)
The following code will print the last 50 years of Sundays starting with the most recent Sunday.
let cal = Calendar.current
// Get the date of 50 years ago today
let stopDate = cal.date(byAdding: .year, value: -50, to: Date())!
// We want to find dates that match on Sundays at midnight local time
var comps = DateComponents()
comps.weekday = 1 // Sunday
// Enumerate all of the dates
cal.enumerateDates(startingAfter: Date(), matching: comps, matchingPolicy: .previousTimePreservingSmallerComponents, repeatedTimePolicy: .first, direction: .backward) { (date, match, stop) in
if let date = date {
if date < stopDate {
stop = true // We've reached the end, exit the loop
} else {
print("\(date)") // do what you need with the date
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With