Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting first day of a week with NSDateComponents : changing year

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?

like image 423
Roman Avatar asked Mar 18 '11 07:03

Roman


2 Answers

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];
like image 200
YvesJusot Avatar answered Nov 08 '22 18:11

YvesJusot


Try this

// adjust them for first day of previous week (Monday)
[comp setWeekday:2];
[comp setWeek:([comp week] - 1)];

Note this solution assumes the first day of the week is Monday.

like image 45
Hanuman Avatar answered Nov 08 '22 19:11

Hanuman