Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get weekdays array from system in Swift?

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

Until now, I can only take the current day, but I'd like to be able to take all weekdays in an array.

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

[ Mon, Tue, Wed... ]

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

[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) 
like image 830
C-Viorel Avatar asked Feb 21 '15 13:02

C-Viorel


1 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 Sun ... Sat array regardless .firstWeekday property of the .calendar. So, you have to 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"]
like image 115
rintaro Avatar answered Sep 30 '22 19:09

rintaro