Home > Software engineering >  Swift Calendar, Weekday starting on Monday instead Sunday
Swift Calendar, Weekday starting on Monday instead Sunday

Time:10-08

Guys I'm following a tutorial to show a calendar in my app using SwiftUI

Everything works but I need: show the names of the week from Monday and not from Sunday and change that days based on the first day of the week

For now I have done this, how can I achieve my goals?

private extension Calendar {
    
        func generateDates(for interval: DateInterval, matching components: DateComponents) -> [Date] {
            var dates = [interval.start]
            enumerateDates(startingAfter: interval.start, matching: components, matchingPolicy: .nextTime) { result, _, stop in
                guard let date = result else { return }
                guard date < interval.end else {
                    stop = true
                    return
                }
                dates.append(date)
            }
            return dates
        }
        
        func generateDays(for interval: DateInterval) -> [Date] {
            generateDates(for: interval, matching: dateComponents([.hour, .minute, .second], from: interval.start))
        }
    }

    func makeDays() -> [Date] {
            guard let firstWeek = calendar.dateInterval(of: .weekOfMonth, for: selectedDate),
                  let lastWeek = calendar.dateInterval(of: .weekOfMonth, for: firstWeek.end - 1) else { return [] }
            let interval = DateInterval(start: firstWeek.start, end: lastWeek.end)
            return calendar.generateDays(for: interval)
        }

CodePudding user response:

Create a custom Gregorian calendar and set the first weekday to Monday

var customCalendar = Calendar(identifier: .gregorian)
customCalendar.firstWeekday = 2
  • Related