【问题标题】:NSCalendar dateFromComponents returns wrong dateNSCalendar dateFromComponents 返回错误的日期
【发布时间】:2011-06-27 08:45:14
【问题描述】:

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

}

【问题讨论】:

标签: cocoa-touch cocoa nsdate nscalendar nsdatecomponents


【解决方案1】:

问题出在时区(我在 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;

}

【讨论】:

  • 奇怪的是,NSCalendar 默认使用本地时区而不是 GMT,不是吗?
  • 完全!今天又忘记了。
猜你喜欢
  • 2013-02-14
  • 2011-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多