在我的 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。
最佳答案
我发现这段代码的行为符合你的预期
[components setYearForWeekOfYear:year];
[components setWeekOfYear:week];
[components setWeekday:2];
它看起来合法,但文档并没有说明太多,所以使用它需要您自担风险。 ^^
关于ios - NSDateComponents 在 2012 年第一周表现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8729527/