1
在我的iOS应用程序中,我必须根据当前日期创建一周。NSDateComponents在2012年的第一周表现得很奇怪
这是一段代码:
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:year];
[components setWeek:week];
[components setWeekday:2];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:components];
在这种特殊情况下的一年是2012年和一周为1。我希望日历返回2012-01-02,因为这是日期2012年1月1日星期一。但相反,它返回2012-12-30。
更新了时区:
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:2012];
[components setWeek:1];
[components setWeekday:2];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone localTimeZone]];
NSDate *date = [gregorian dateFromComponents:components];
仍然返回2012-12-30。
除了2012年的第一个星期,它还是完美的。 – hufkens 2012-01-05 10:29:03
@hufkens我认为结果日期是2012-01-02当地方应用时区。你的结果是什么? – tia 2012-01-05 11:46:55
无论我将其添加为时区,它总是会返回2012-12-30。我尝试过:[格里高利setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@“GMT”]];或[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@“CET”]];或[gregorian setTimeZone:[NSTimeZone localTimeZone]]; – hufkens 2012-01-05 15:30:15