Swift - day of the week at current location currentCalendar ()

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 - 4, but today is the 3rd day of the week in Bulgaria. Is the 4th day of the week in the US today? And how to determine when a week starts in different countries and regions? In my region and iPhone calendar, a Bulgarian calendar and a locale are installed, and he knows that the week starts on Monday on my iMac, but when I execute the code, he writes me 4 ...

+6
source share
1 answer

For the Gregorian calendar, the weekday property of NSDateComponents always 1 for Sunday, 2 for Monday, etc.

 NSCalendar.currentCalendar().firstWeekday 

gives (index) the first day of the week in the current region, which can be 1 in the USA and 2 in Bulgaria. therefore

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

- day of the week according to your language. As single line:

 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 } 
+18
source

Source: https://habr.com/ru/post/978738/


All Articles