List of days in current month

Try this:

func getDaysSimple(for month: Date) -> [Date] {
    
    //get the current Calendar for our calculations
    let cal = Calendar.current
    //get the days in the month as a range, e.g. 1..<32 for March
    let monthRange = cal.range(of: .day, in: .month, for: month)!
    //get first day of the month
    let comps = cal.dateComponents([.year, .month], from: month)
    //start with the first day
    //building a date from just a year and a month gets us day 1
    var date = cal.date(from: comps)!

    //somewhere to store our output
    var dates: [Date] = []
    //loop thru the days of the month
    for _ in monthRange {
        //add to our output array...
        dates.append(date)
        //and increment the day
        date = cal.date(byAdding: .day, value: 1, to: date)!
    }
    return dates
}

Usage:

print(getDaysSimple(for: .now)) 

//running on 2022-03-02 returns the following result:
//[2022-03-01 08:00:00 +0000, 2022-03-02 08:00:00 +0000, 2022-03-03 08:00:00 +0000, 
//2022-03-04 08:00:00 +0000, 2022-03-05 08:00:00 +0000, 2022-03-06 08:00:00 +0000, 
//2022-03-07 08:00:00 +0000, 2022-03-08 08:00:00 +0000, 2022-03-09 08:00:00 +0000,
//2022-03-10 08:00:00 +0000, 2022-03-11 08:00:00 +0000, 2022-03-12 08:00:00 +0000, 
//2022-03-13 08:00:00 +0000, 2022-03-14 07:00:00 +0000, 2022-03-15 07:00:00 +0000,
//2022-03-16 07:00:00 +0000, 2022-03-17 07:00:00 +0000, 2022-03-18 07:00:00 +0000,
//2022-03-19 07:00:00 +0000, 2022-03-20 07:00:00 +0000, 2022-03-21 07:00:00 +0000, 
//2022-03-22 07:00:00 +0000, 2022-03-23 07:00:00 +0000, 2022-03-24 07:00:00 +0000,
//2022-03-25 07:00:00 +0000, 2022-03-26 07:00:00 +0000, 2022-03-27 07:00:00 +0000,
//2022-03-28 07:00:00 +0000, 2022-03-29 07:00:00 +0000, 2022-03-30 07:00:00 +0000,
//2022-03-31 07:00:00 +0000]

Note that the dates are listed for UTC+00:00 adjusted for your locale. I am currently in UTC-08:00, so the start of the day for me is 08:00:00 at the beginning of March, but since Daylight Saving Time starts the second Sunday in March, it switches to 07:00:00 on the 14th since that time zone is UTC-07:00.

With this array of Date objects, you should be able to create a list in SwiftUI or whatever you want to do with it.

1 Like