我希望使用Swift找到过去50年中每个星期日的日期。我认为'枚举日期' (日历的实例方法)可能会有所帮助。但我无法弄清楚如何使用它。
O(n)
答案 0 :(得分:6)
以下代码将打印从最近的星期日开始的星期日的最后50年。
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
}
}
}