使用 NSCalendar 查找星期日和星期一 Swift

Find Sunday and Monday with NSCalendar Swift

大家好,我正在使用 NSCalendar.

制作日历

我需要找到一个月内的每个 星期日星期一 以更改单元格颜色,这与其他日子不同..

你能帮我理解如何找到(通过使用 NSCalendar)每个 星期日星期一 的当前月份?

可以获取月的起始结束日期,枚举一个月中的所有日期(可以使用中午),检查结果日期是否小于结束日期,否则停止枚举。然后你只需要检查日期的工作日是否等于星期日或星期一(1或2)并将其添加到集合中:


extension Date {
    func startOfMonth(using calendar: Calendar = .current) -> Date {
        calendar.dateComponents([.calendar, .year, .month], from: self).date!
    }
    func startOfNextMonth(using calendar: Calendar = .current) -> Date {
        calendar.date(byAdding: .month, value: 1, to: startOfMonth(using: calendar))!
    }
    func weekday(using calendar: Calendar = .current) -> Int {
        calendar.component(.weekday, from: self)
    }
}

let now = Date()
let calendar = Calendar(identifier: .iso8601)
let start = now.startOfMonth(using: calendar)
let end = now.startOfNextMonth(using: calendar)
var dates: [Date] = []

calendar.enumerateDates(startingAfter: start, matching: DateComponents(hour: 12), matchingPolicy: .strict) { (date, _, stop) in
    guard let date = date, date < end else {
        stop = true
        return
    }
    if 1...2 ~= date.weekday(using: calendar) { dates.append(date) }
}

dates.forEach {
    print([=11=].description(with: .current))
}

这将打印

Sunday, October 4, 2020 at 12:00:00 PM BRST
Monday, October 5, 2020 at 12:00:00 PM BRST
Sunday, October 11, 2020 at 12:00:00 PM BRST
Monday, October 12, 2020 at 12:00:00 PM BRST
Sunday, October 18, 2020 at 12:00:00 PM BRST
Monday, October 19, 2020 at 12:00:00 PM BRST
Sunday, October 25, 2020 at 12:00:00 PM BRST
Monday, October 26, 2020 at 12:00:00 PM BRST