Finding the locale-dependent first day of the week

天大地大妈咪最大 提交于 2020-01-03 16:45:08

问题


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'?


回答1:


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.




回答2:


An smarter way for old style for those who do not want to set calendar firstWeekday.

NSDate *date = [NSDate dateWithTimeIntervalSince1970:1483620311.228]; 
NSLog(@"current date ===> : %@", date);
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *previousMonday = [calendar nextDateAfterDate:date 
                                    matchingUnit:NSCalendarUnitWeekday  
                                           value:2 //use 1-7 for Sunday to Saturday week day.
                                         options:NSCalendarMatchNextTime | NSCalendarSearchBackwards];
NSLog(@"previousMonday date ===> : %@", previousMonday); 


来源:https://stackoverflow.com/questions/23668942/finding-the-locale-dependent-first-day-of-the-week

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!