I develop an app that needs to get the current week. I tried this:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *dateString = @"1-1-2011";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comp = [gregorian components:NSWeekCalendarUnit fromDate:dateFromString];
NSLog(@"%d", comp.week);
[dateFormatter release];
}
but it shows me 52. Which is actually a wrong result. Please, suggest me any ideas.
Thanks in advance.
The week date depends on which numbering standard is in use. For instance, the ISO-8601 standard defines week 1 of a year as “the week with the year’s first Thursday in it”.
The first of January 2011 was a Saturday, which means the following week was week 1 of 2011, making the week 27.12.2010–2.1.2011 week 52 of 2010.
Also, there’s several incompatible standards for when weeks start or end and how weeks in a year are numbered. This makes week numbers a confusing way to specify a date range and the best solution to avoid using them.
From the documentation to NSCalendar, it seems you could also use
setMinimumDaysInFirstWeek:to adjust the way it numbers weeks.