Search code examples
objective-cios5nsdatensdateformatternscalendar

Getting wrong week number in iOS


I am trying to get week Number in iPhone. I am using this piece of code

NSNumber* getWeek() {
    NSDate *currDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"w.ee"];
    NSString *dateString = [dateFormatter stringFromDate:currDate];
    NSNumberFormatter *weekNumber = [[NSNumberFormatter alloc] init];
    [weekNumber setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber *week = [weekNumber numberFromString:dateString];
    [weekNumber release];
    return week;
 }

However, I have difference result, at simulator is ok, but when I ran in iPhone this got me "0" IOS 5.0.1

Any helps?


Solution

  • Using a string for the week number is not the best way to get to this kind of information. NSCalendar and NSDateComponents have been designed specifically for this kind of calculation:

    NSDate *currDate = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [calendar components:NSWeekOfYearCalendarUnit|NSWeekdayCalendarUnit fromDate:currDate];
    NSLog(@"%d %d", components.weekOfYear, components.weekday);
    

    You can specify a list of components in the calendar call (line 3) as seen in the example note that only the specified components are guaranteed to be filled in the NSDateComponents object.