1

在我的 iOS 应用程序中,我必须根据当前日期创建一周。

这是一段代码:

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 周的星期一日期。但它返回 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。

4

1 回答 1

-1

我发现这段代码的行为如你所料

[components setYearForWeekOfYear:year];
[components setWeekOfYear:week];
[components setWeekday:2];

它看起来是合法的,但文件并没有说太多,所以使用它需要您自担风险。^ ^

于 2012-01-04T20:08:34.433 回答