【问题标题】:NSDateComponents behaving strange in the first week of 2012NSDateComponents 在 2012 年的第一周表现异常
【发布时间】:2012-01-06 00:08:15
【问题描述】:

在我的 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。

【问题讨论】:

    标签: ios nscalendar nsdatecomponents


    【解决方案1】:

    我发现这段代码的行为和你期望的一样

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

    它看起来合法,但文档并没有说太多,因此使用它需要您自担风险。 ^^

    【讨论】:

    • @hufkens 我很肯定结果日期是 2012-01-02 应用本地时区。你的结果是什么?
    • 无论我添加什么作为时区,它总是返回 2012-12-30。我试过:[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];或 [gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CET"]];或 [gregorian setTimeZone:[NSTimeZone localTimeZone]];
    • 代码可以在原始消息中找到。该示例使用 localTimeZone。
    • 你没有使用我建议的方法?
    • 感谢您的帮助,但您指的具体方法是什么?在更新的示例中,我将 localTimeZone 应用于 NSCalendar。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    相关资源
    最近更新 更多