【问题标题】:NSCalendar and NSDateComponents returning unexpected dateNSCalendar 和 NSDateComponents 返回意外的日期
【发布时间】:2011-12-27 10:45:06
【问题描述】:

我正在尝试从 NSCalendar 和 NSDateComponents 创建一个 NSDate:

    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setTimeZone:[NSTimeZone localTimeZone]]; 
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setDay:[self.day intValue]];
    [components setMonth:[self.month intValue]];
    [components setYear:[self.year intValue]];
    self.date = [calendar dateFromComponents:components];

当日、月、年是:9/31/2011时,NSDate 是 10/1/2011。在测试未更改 NSDate 之后,我为 NSCalendar 设置了时区。我也试过了

[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];

这让我回到了 2011 年 9 月 30 日。有人看到我计算的方式有错误吗?

谢谢。

【问题讨论】:

    标签: objective-c cocoa nsdate nscalendar nsdatecomponents


    【解决方案1】:

    嗯,9 月 31 日真的是 10 月 1 日。

    但组件必须知道在哪个日历中工作。以下代码来自苹果

    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setDay:6];
    [comps setMonth:5];
    [comps setYear:2004];
    NSCalendar *gregorian = [[NSCalendar alloc]
        initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *date = [gregorian dateFromComponents:comps];
    [comps release];
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多