Search code examples
cocoa-touchcocoansdatenscalendarnsdatecomponents

NSCalendar dateFromComponents returns wrong date


I'm writing a Category on NSDate to create an NSDate from an ISO 8601 string representation (YYYYMMDD).

Even though I pass 20010226, I get back 2001-02-25 23:00:00 +0000. what am I doing wrong?

This is the code:

-(id) initWithISO8601Date: (NSString *) iso8601Date{
    // Takes a date in the YYYYMMDD form


    int year = [[iso8601Date substringWithRange:NSMakeRange(0, 4)] integerValue];
    int month = [[iso8601Date substringWithRange:NSMakeRange(4, 2)] integerValue];
    int day = [[iso8601Date substringWithRange:NSMakeRange(6,2)] integerValue];

    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setYear:year];
    [comps setMonth:month];
    [comps setDay:day];


    self = [[NSCalendar currentCalendar] dateFromComponents:comps];
    NSLog(@"%@", self);

    [comps release];

    return self;

}

Solution

  • The problem was the Time Zone (I'm on GMT -1). The correct code is:

    -(id) initWithISO8601Date: (NSString *) iso8601Date{
        // Takes a date in the YYYYMMDD form
        int year = [[iso8601Date substringWithRange:NSMakeRange(0, 4)] integerValue];
        int month = [[iso8601Date substringWithRange:NSMakeRange(4, 2)] integerValue];
        int day = [[iso8601Date substringWithRange:NSMakeRange(6,2)] integerValue];
    
        NSDateComponents *comps = [[NSDateComponents alloc] init];
        [comps setYear:year];
        [comps setMonth:month];
        [comps setDay:day];
    
        NSCalendar *cal = [NSCalendar currentCalendar];
        [cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
        self = [cal dateFromComponents:comps];
    
    
        [comps release];
    
        return self;
    
    }