Swift - Weekday by current location by currentCalendar() Swift - Weekday by current location by currentCalendar() swift swift

Swift - Weekday by current location by currentCalendar()


For the Gregorian calendar, the weekday property of NSDateComponents is always1 for Sunday, 2 for Monday etc.

NSCalendar.currentCalendar().firstWeekday

gives the (index of the) first weekday in the current locale, that could be 1 in USAand 2 in Bulgaria. Therefore

var dayOfWeek = dateComps.weekday + 1 - calendar.firstWeekdayif dayOfWeek <= 0 {    dayOfWeek += 7}

is the day of the week according to your locale. As a one-liner:

let dayOfWeek = (dateComps.weekday + 7 - calendar.firstWeekday) % 7 + 1

Update for Swift 3:

let calendar = Calendar.currentvar dayOfWeek = calendar.component(.weekday, from: Date()) + 1 - calendar.firstWeekdayif dayOfWeek <= 0 {    dayOfWeek += 7}


If you want to know which are the weekend days you can use this extension:

extension Calendar {    /// Return the weekSymbol index for the first week end day    var firstWeekendDay: Int {        let firstWeekDay = self.firstWeekday        return (firstWeekDay - 2) >= 0 ? firstWeekDay - 2 : firstWeekDay - 2 + 7    }    /// Return the weekSymbol index for the second week end day    var secondWeekendDay: Int {        let firstWeekDay = self.firstWeekday        return (firstWeekDay - 1) >= 0 ? firstWeekDay - 1 : firstWeekDay - 1 + 7    }}