我正在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;
}
答案 0 :(得分: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;
}