Ben Packard Ben Packard - 1 year ago 112
Objective-C Question

Finding the locale-dependent first day of the week

Given an

, 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 Source

Try changing:

[components setWeekday:1];


[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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download