Ben Packard Ben Packard - 1 month ago 25
Objective-C Question

Finding the locale-dependent first day of the week

Given an

NSDate
, how do I find the first day of that date's week, given the user's locale. For example, I've heard that some countries treat Monday as the first day of the week and others use Sunday. I need to return the preceding Monday in the first case but the preceding Sunday in the latter case.

My best effort thus far always returns the preceding Sunday, regardless of the device settings applied:

NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setLocale:[NSLocale currentLocale]];
NSDateComponents *components = [calendar components:NSYearForWeekOfYearCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit fromDate:originalDate];
[components setWeekday:1];
NSDate *firstDayOfWeek = [calendar dateFromComponents:components];


Bonus question: on iOS, which setting drives this? Is it the 'Region Format'?

Answer

Try changing:

[components setWeekday:1];

to:

[components setWeekday:[calendar firstWeekday]];

You should also remove the NSYearForWeekOfYearCalendarUnit and NSWeekCalendarUnit components.

Bonus Question: "Region Format" should be the setting that changes the first day of the week.