Search for the locally dependent first day of the week

Given NSDatehow I can find the first day of this week, given the user's locale. For example, I heard that some countries view Monday as the first day of the week, while others use Sunday. I need to return the previous Monday in the first case, but on the previous Sunday in the latter case.

My best effort so far is always returning the previous 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 installs this? Is this the "Region Format"?

+4
source share
2 answers

Try changing:

[components setWeekday:1];

at

[components setWeekday:[calendar firstWeekday]];

NSYearForWeekOfYearCalendarUnit NSWeekCalendarUnit.

: " " , .

+5

, 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); 
0

Source: https://habr.com/ru/post/1540630/


All Articles