How to get an array of weekdays from the system in Swift?

How can I take an array of days of the week from the system (from NSDate , I think)?

So far, I can only use the current day, but I would like to be able to accept all working days in an array.

If the first day of the week is set to Monday, my array will look like this:

 [ Mon, Tue, Wed... ] 

If the first day of the week is Sunday, my array will look like this:

 [Sun, Mon, Tue... ] 

code:

 let dateNow = NSDate() let calendar = NSCalendar.currentCalendar() let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond | .CalendarUnitYear , fromDate: dateNow) /*This is the way how i take system time */ let format = NSDateFormatter() format.dateFormat = "EEE" stringDay = format.stringFromDate(dateNow) 
+6
source share
2 answers

Try these properties :

 let fmt = NSDateFormatter() fmt.weekdaySymbols // -> ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] fmt.shortWeekdaySymbols // -> ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] fmt.veryShortWeekdaySymbols // -> ["S", "M", "T", "W", "T", "F", "S"] fmt.standaloneWeekdaySymbols // -> ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] fmt.shortStandaloneWeekdaySymbols // -> ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] fmt.veryShortStandaloneWeekdaySymbols // -> ["S", "M", "T", "W", "T", "F", "S"] 

It seems they always return a Sun ... Sat array regardless of the .firstWeekday property. Therefore, you must rotate it manually.

 let firstWeekday = 2 // -> Monday var symbols = fmt.shortWeekdaySymbols symbols = Array(symbols[firstWeekday-1..<symbols.count]) + symbols[0..<firstWeekday-1] // -> ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] 
+21
source

If you want to have Monday as your first day, you can use this extension.

 extension SequenceType where Generator.Element == String { func mondayFirst(withSunday: (Bool)) -> [String] { var tempWeek = self as! [String] let tempDay = tempWeek.first tempWeek.removeFirst() if (!withSunday) { tempWeek.append(tempDay!) } return tempWeek } } 
0
source

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


All Articles