Assuming that you want the Sunday (first day) and Saturday (last day) of a given week, this code will do what you want (for clarity I have created two methods, but you could combine them back in to one) -
+ (NSDate *)firstDayOfWeek:(NSInteger)weekNumber inYear:(NSInteger)year
{
NSDateComponents *comps=[[NSDateComponents alloc]init];
[comps setWeekday:1]; //Change this to 2 if you want Monday rather than Sunday
[comps setWeekOfYear:weekNumber];
[comps setYear:year];
[comps setYearForWeekOfYear:year];
NSCalendar *cal=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *newDate=[cal dateFromComponents:comps];
return newDate;
}
+ (NSDate *)lastDayOfWeek:(NSInteger)weekNumber inYear:(NSInteger)year
{
NSDateComponents *comps=[[NSDateComponents alloc]init];
[comps setWeekday:7]; //Change this to 6 if you want Friday rather than Saturday
[comps setWeekOfYear:weekNumber];
[comps setYear:year];
[comps setYearForWeekOfYear:year];
NSCalendar *cal=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *newDate=[cal dateFromComponents:comps];
return newDate;
}
One important point is the [comps setYearForWeekOfYear:year];
- otherwise you may get unexpected results for week 1 - By default you will get the "last" week 1 in the year, which is also week 1 of the following year, so you end up a year later than you expected.
If you wanted to combine the two into one method, I would use an NSDictionary
rather than an NSArray
-
+(NSDictionary *)firstAndLastDayOfWeek:(NSInteger)weekNumber inYear:(NSInteger)year
{
NSDateComponents *comps=[[NSDateComponents alloc]init];
[comps setWeekday:1];
[comps setWeekOfYear:weekNumber];
[comps setYear:year];
[comps setYearForWeekOfYear:year];
NSCalendar *cal=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *firstDay=[cal dateFromComponents:comps];
[comps setWeekday:7];
NSDate *lastDay=[cal dateFromComponents:comps];
return @{@"firstDay":firstDay,@"lastDay":lastDay};
}