Swift - Weekday by current location by currentCalendar()
Asked Answered
A

3

14

Today is Wednesday and I have this code

let calendar:NSCalendar = NSCalendar.currentCalendar()
let dateComps:NSDateComponents = calendar.components(.CalendarUnitWeekday , fromDate: NSDate())
let dayOfWeek:Int = dateComps.weekday

dayOfWeek is 4, but today is 3rd day of the week in Bulgaria. Is in USA today is 4th day of the week? And how to determine when the week starts in different countries and regions ? On my iPhone locale and calendar are set to Bulgarian calendar and locale and it knows that the week starts on Monday on my iMac also, but when I execute code it writes me 4...

Augment answered 26/11, 2014 at 15:32 Comment(0)
S
35

For the Gregorian calendar, the weekday property of NSDateComponents is always 1 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 USA and 2 in Bulgaria. Therefore

var dayOfWeek = dateComps.weekday + 1 - calendar.firstWeekday
if 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.current
var dayOfWeek = calendar.component(.weekday, from: Date()) + 1 - calendar.firstWeekday
if dayOfWeek <= 0 {
    dayOfWeek += 7
}
Scott answered 26/11, 2014 at 15:44 Comment(1)
To clarify this for others, I don't believe that calendar.firstWeekday is the "index of the first weekday". A value of 1 corresponds to Sunday and 2 corresponds to Monday, same as with NSDateComponents. Please correct me if I'm missing something.Thulium
R
0

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
    }

}
Rattrap answered 23/11, 2019 at 17:2 Comment(0)
R
-1

Set firstWeekday on your Calendar.

https://developer.apple.com/documentation/foundation/calendar/2293656-firstweekday

Removed answered 23/1, 2024 at 21:52 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.