I wants to display dates/days from Monday to Friday excluding Saturday/Sunday as mentioned in the image below.
My Scenario:
- When screen loads the current week should display.
- On previous button click (DisplayedWeek - 1)
- On Next button click (DisplayedWeek + 1).
My Work,
After some research this is what i have tried.
let calendar = Calendar.current
let currentDate = calendar.startOfDay(for: Date())
/* value = 0 for current,
value = 1 for next,
value = -1 for previous week.
*/
let nextWeek:Date = calendar.date(byAdding: .weekOfMonth, value: 1, to: currentDate)! as Date
let dayOfWeek = calendar.component(.weekday, from: nextWeek)
let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: nextWeek)!
let days = (weekdays.lowerBound ..< weekdays.upperBound).flatMap {
calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: nextWeek)
}.filter { !calendar.isDateInWeekend($0) }
// Week Days from monday to friday
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
for date in days {
print(formatter.string(from: date))
}
In my case if the day is Saturday or Sunday it should display next week but it is displaying the same week.