Get every days from given month of particular Year

Viewed 2601

Is it possible to get an array of Date for each day of a given Month and Year from Calendar components (Swift 3)

Currently I just find a way to get a count of days but nothing more.

The purpose is to develop my custom calendar but I get stuck to this phase...

The extension I'm trying to write will look like this:

extension Date 
{
    func getAllDays() -> [Date]
}

Or a method like that:

func getAllDays(month: Int, year: Int) -> [Date]
2 Answers

Here a little bit better code for doing the same

extension Date {

    var startOfMonth: Date {
            return Calendar.iso8601.date(from: Calendar.iso8601.dateComponents([.year, .month], from: self))!
        }

    var daysOfMonth: [Date] {
        let startOfMonth = self.startOfMonth
        let calendar = Calendar.current
        let range = calendar.range(of: .day, in: .month, for: self)!
        return range.compactMap{ calendar.date(byAdding: .day, value: $0, to: startOfMonth)}
    }
}


extension Calendar {
    static let iso8601 = Calendar(identifier: .iso8601)
}
Related