Getting first day of a week with NSDateComponents : changing year

Roman picture Roman · Mar 18, 2011 · Viewed 9.8k times · Source

Hello I have a problem with setting a firstWeekDay, here is what I do:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
comp = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit) fromDate:targetDate];
[comp setWeekday:2];

NSDate *firstWeekDay = [gregorian dateFromComponents:comp];

If Saturday 2011-01-01 is targetDate, the firstWeekDay in my calendar appears to be Monday 2011-12-26, but in fact it should be Monday 2010-12-26. How can I make it right?

Answer

YvesJusot picture YvesJusot · Jan 6, 2012

To fix this problem, Add NSYearForWeekOfYearCalendarUnit in the NSDateComponents.

Ex:

NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* comps = [calendar components:NSYearForWeekOfYearCalendarUnit |NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayCalendarUnit fromDate:curDate];

[comps setWeekday:2]; // 2: monday
firstDayOfTheWeek = [calendar dateFromComponents:comps];
[comps setWeekday:7]; // 7: saturday
lastDayOfTheWeek = [calendar dateFromComponents:comps];