In order to get the days of the week I use:
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
NSArray *weekdays = [dateFormatter shortWeekdaySymbols];
Weekdays gives me an array with the days names but it begins by Sunday. For some reasons I want this array to begin by Monday or Sunday depending on the localisation settings of the device.
Is there a way to do it?
You can get the 1-based index of the first weekday of the current locale from the -firstWeekday
method of an NSCalendar
object with the current locale. Then you can modify your week names array accordingly:
// get week day names array
NSArray *weekdays = self.shortWeekdaySymbols;
// adjust array depending on which weekday should be first
NSUInteger firstWeekdayIndex = [NSCalendar currentCalendar].firstWeekday - 1;
if (firstWeekdayIndex) {
NSRange firstRange = NSMakeRange(firstWeekdayIndex, weekdays.count - firstWeekdayIndex);
NSRange lastRange = NSMakeRange(0, firstWeekdayIndex);
NSArray *firstArray = [weekdays subarrayWithRange:firstRange];
NSArray *lastArray = [weekdays subarrayWithRange:lastRange];
weekdays = [firstArray arrayByAddingObjectsFromArray:lastArray];
}
NSLog(@"%@", weekdays);
I don't have the iPhone SDK but AFAIK these APIs should be all available there and behave the same way as on OS X.
Achieved a result similar to hasseg in Swift using:
var symbols = dateFormatter.shortWeekdaySymbols as! [String]
let firstDayIndex = calendar.firstWeekday - 1
if firstDayIndex > 0 {
var sub = symbols[0..<firstDayIndex]
symbols.removeRange(Range<Int>(start:0, end:firstDayIndex))
symbols += sub
}
You need to use NSCalender to change the start day of your week from programatically.
NSCalendar *_calendar;
_calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
_calendar.timeZone = [NSTimeZone localTimeZone];
[_calendar setFirstWeekday:2];// Sunday == 1, Saturday == 7
_calendar.locale = [NSLocale currentLocale];
NSDateComponents *dateComponent = [_calendar components:(NSCalendarUnitWeekOfYear | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear) fromDate:[NSDate date]];
NSDate *now = [NSDate date];
NSDateComponents *comp = [_calendar components:NSCalendarUnitYear fromDate:now];
[comp setWeekOfMonth:dateComponent.weekOfYear]; //Week number.
[comp setWeekday:2];
NSDate * weekstartPrev = [_calendar dateFromComponents:comp];
like the myexec solution but more generic and equally concise
let numDays = Calendar.current.weekdaySymbols.count
let first = Calendar.current.firstWeekday
let end = first + numDays - 1
let days = (first...end).map {Calendar.current.weekdaySymbols[$0 % numDays]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With