Одним из решений является использование метода Calendar nextDate(after:matching:matchingPolicy:)
, передающего экземпляр DateComponents
с желаемым установленным днем.
extension Calendar {
func count(of day: Int, between startDate: Date, and endDate: Date) -> Int {
let matchComps = DateComponents(day: day)
var dates = [Date]()
var date = startDate
while let matchingDate = self.nextDate(after: date, matching: matchComps, matchingPolicy: .nextTime), matchingDate <= endDate {
dates.append(matchingDate)
date = matchingDate
}
print("Found \(dates) between \(startDate) and \(endDate)")
return dates.count
}
}
let startDate = Calendar.current.date(from: DateComponents(year: 2019, month: 7, day: 11))!
let endDate = Calendar.current.date(from: DateComponents(year: 2020, month: 7, day: 1))!
let count = Calendar.current.count(of: 8, between: startDate, and: endDate)
Вывод:
Найдено [2019-08-08 06:00:00 +0000, 2019-09-08 06:00:00 +0000, 2019-10-08 06:00:00 +0000, 2019-11-08 07:00:00 +0000, 2019-12-08 07:00:00 +0000, 2020-01-08 07:00:00 +0000, 2020-02-08 07:00:00 +0000, 2020-03-08 07:00:00 +0000, 2020-04-08 06:00:00 +0000, 2020-05-08 06:00:00 +0000, 2020-06-08 06:00:00 +0000] между 2019-07-11 06:00:00 +0000 и 2020-07-01 06:00:00 + 0000
Конечно, точный результат будет зависеть от вашего часового пояса.