NSCalendar dateFromComponents返回错误的日期

cfi*_*her 2 cocoa cocoa-touch nsdate nscalendar nsdatecomponents

我正在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;

}
Run Code Online (Sandbox Code Playgroud)

cfi*_*her 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;

}
Run Code Online (Sandbox Code Playgroud)

  • 奇怪的是,NSCalendar默认使用本地timeZone而不是GMT,不是吗? (2认同)