I need this for getting data in a graph for week basis. This one does not work for me. The date that it returns is first of January of the selected year. Any ideea?
-(NSDate*) getFirstDateOfTheWeek:(NSString*) weekNr andYear: (NSString*) theYear {
int intYear = [theYear intValue];
int intWeek = [weekNr intValue];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setLocale:[NSLocale currentLocale]];
NSDateComponents * comp = [[NSDateComponents alloc] init];
[comp setYear:intYear];
[comp setWeek:intWeek];
NSDate *dateOfFirstDay = [gregorian dateFromComponents:comp];
NSDateComponents *dateComponents =
[gregorian components:NSWeekdayCalendarUnit|NSWeekCalendarUnit|NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit fromDate:dateOfFirstDay];
int year = [dateComponents year];
int month = [dateComponents month];
int day = [dateComponents day];
dateOfFirstDay= [gregorian dateFromComponents:dateComponents];
return dateOfFirstDay;
}
You should setWeekday in your NSDateComponents in addition you setYear and setWeek.
Then when grabbing the new components you don’t need many of the flags, as you really only need the day (and the others for debugging):