Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

}
like image 565
cfischer Avatar asked Aug 30 '26 02:08

cfischer


1 Answers

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;

}
like image 122
cfischer Avatar answered Sep 04 '26 08:09

cfischer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!