Search code examples
iosswiftweekday

How to get weekday in Swift regardless of the locale settings?


In my iOS app user can choose on which day to have certain action active and I am saving each selection as a raw value of OptionSet. This all works great.

But I need a way to map current day to the selected options. How can I get some kind of constants for weekdays that do not changed based on whether week starts on Sunday or Monday based on selected locale?

This:

let weekDay = Calendar.current.component(.weekday, from: Date())

Seems like a solution but the Int constant is going to vary right based on a locale? According to very short docs from Apple this should be 1 for Sunday in Gregorian calendar.

Is there any way how I can get weekday from Date that will be always same?

I would like to map these constants to my OptionSet flags and based on that decide whether action should be active in a given day.

Thanks.


Solution

  • You are mixing up weekday and firstWeekday.

    The weekday component is independent of the locale, in the Gregorian Calendar 1 is always Sunday, 2 Monday etc.