首页 文章

NSCalendar和NSDateComponents返回意外日期

提问于
浏览
0

我正在尝试从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 . 我在测试后设置NSCalendar的时区,但没有改变NSDate . 我也试过了

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

这让我回来 9/30/2011 . 任何人都看到我计算这个错误的方式?

谢谢 .

1 回答

  • 3

    那么,9月31日真的是10月10日 .

    但是组件必须知道要在哪个日历中工作 . 以下代码来自apple

    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];
    

相关问题