【问题标题】:How to check how many times a specific day occurs between two dates?如何检查特定日期在两个日期之间发生了多少次?
【发布时间】:2019-11-07 04:27:33
【问题描述】:

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

我有 3 个价值观。它们是 startDate、endDate 和 specificDate(一个月中的特定日期)。

假设:

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 中以编程方式实现或实现两个日期之间的特定日期出现次数计算?

以上数值只是举例。这些字段可以有任何值。

【问题讨论】:

    标签: swift date calendar


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-22
      • 2012-09-19
      • 1970-01-01
      • 2020-01-31
      • 1970-01-01
      • 1970-01-01
      • 2013-02-05
      • 1970-01-01
      相关资源
      最近更新 更多