如何检查特定日期在两个日期之间出现了多少次?

How to check how many times a specific day occurs between two dates?

我正在尝试计算 Swift 中两个日期(即开始日期和结束日期)之间特定日期出现的次数。我会试着用一个例子来解释。

我有3个价值观。它们是开始日期、结束日期和特定日期(一个月中的特定日期)。

假设:

specificDate = 8    // specific day in a month
startDate = 07-11-2019
endDate = 07-01-2020

从上面的例子我可以说 specifcDate 8 在 startDate 和 endDate 之间出现了 2 次,即在 11 月 8 日和 12 月 8 日。

如何在 Swift 中以编程方式实现或实现两个日期之间的特定日期出现次数计算?

以上数值仅供参考。这些字段可以有任何值。

一种解决方案是使用 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)

输出:

Found [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] between 2019-07-11 06:00:00 +0000 and 2020-07-01 06:00:00 +0000

当然,确切的输出将取决于您的时区。