[SOLVED] How to get all days in current week in swift

Issue

I am making an application where I need to get the day of the year for all days in the current week.
To achieve this, I am looking for a result similar to below (Today is Thursday the 23rd of March)

Monday = 79
Tuesday = 80
Wednesday = 81
Thursday = 82
Friday = 83

Saturday and Sunday can be included, however my application only needs weekdays rather then weekends. Today is day 82

Solution

To get the weekdays of the week, it is:

let calendar = Calendar.current
let today = calendar.startOfDay(for: Date())
let dayOfWeek = calendar.component(.weekday, from: today)
let days = calendar.range(of: .weekday, in: .weekOfYear, for: today)!
    .compactMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: today) }
    .filter { !calendar.isDateInWeekend($0) }

To display that as "Thursday = 82", it is

let formatter = DateFormatter()
formatter.dateFormat = "eeee' = 'D"
for date in days {
    print(formatter.string(from: date))
}

Or

let strings = days.map { formatter.string(from: $0) }

Answered By – Rob

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *