Pregunta

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

¿Fue útil?

Solución

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.

Otros consejos

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); 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top