Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use enumerateDate in Swift 3 to find all Sundays the last 50 years?

Tags:

swift

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)
like image 761
Wismin Avatar asked Dec 24 '22 21:12

Wismin


1 Answers

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
        }
    }
}
like image 60
rmaddy Avatar answered May 18 '23 18:05

rmaddy