Hi all I am working on a calendar using NSCalendar
.
I need to find every Sunday and Monday within the month to change the cell color unlike other days ..
Can you help me understand how to find (through the use of NSCalendar
) every Sunday and Monday of the current month?
You can get the start end end of the month, enumerate all days in a month (you can use noon), check if the resulting day is less than the end date otherwise stop the enumeration. Then you just need to check if the date's weekday is equal to Sunday or Monday (1 or 2) and add it to the collection:
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($0.description(with: .current))
}
This will print
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