2

我正在 NSDate 上编写一个类别,以从 ISO 8601 字符串表示 (YYYYMMDD) 创建一个 NSDate。

即使我通过了 20010226,我还是回到了 2001-02-25 23:00:00 +0000。我究竟做错了什么?

这是代码:

-(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;

}
4

1 回答 1

10

问题是时区(我在 GMT -1)。正确的代码是:

-(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;

}
于 2011-06-27T08:54:29.167 回答