gpt4 book ai didi

cocoa-touch - NSCalendar dateFromComponents 返回错误的日期

转载 作者:行者123 更新时间:2023-12-03 16:24:05 25 4
gpt4 key购买 nike

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

}

最佳答案

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

}

关于cocoa-touch - NSCalendar dateFromComponents 返回错误的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6490434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com