How can I calculate the date having only the week number and day of the week?
E.g. Week 24, Tuesday, 2012, where weeks start on Monday.
How can I calculate the date having only the week number and day of the week?
E.g. Week 24, Tuesday, 2012, where weeks start on Monday.
Very conveniently, NSCalendar will do all the math for you. First, set up the parameters using NSDateComponents:
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setWeek:24];
[comps setWeekday:3]; //map weekday names to numbers (e.g., Sunday is 1)
[comps setYear:2012];
Then create a Gregorian calendar with those date components:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
And grab your NSDate:
NSDate *date = [gregorian dateFromComponents:comps];
NSDate *now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comp = [gregorian components:NSYearCalendarUnit fromDate:now];
[comp setWeek:24];
[comp setDay:1];
NSDate *resultDate = [gregorian dateFromComponents:comp];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMM d, yyyy"];
NSString *myDateString = [formatter stringFromDate:resultDate];
[gregorian release]; // Clean up allocated objects by releasing them
[formatter release];
NSString * date = [NSString stringWithFormat:@"Week of %@", myDateString];