dateFromComponents返回错误的值

时间:2015-05-25 18:09:35

标签: ios objective-c nsdate nsdatecomponents

我试图设置[NSDate date]的月份和年份,但函数dateFromComponents返回错误的值,这是我的代码:

    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian]; // Setup an NSCalendar
NSDateComponents *components = [gregorianCalendar components: NSUIntegerMax fromDate: [NSDate date]]; // Setup NSDateComponents
[components setTimeZone:[NSTimeZone defaultTimeZone]];
[components setMonth:monthInt];
[components setYear:yearInt];

// Setup the new date
NSDate *dateToCompare = [gregorianCalendar dateFromComponents: components];

yearInt是2014年,monthInt是12,但它报告的是12-2015而不是2014年,为什么会这样?

谢谢!

1 个答案:

答案 0 :(得分:0)

你只需要放置你需要的位运算符,试试这个:

    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian]; // Setup an NSCalendar
NSDateComponents *components = [gregorianCalendar components: NSCalendarUnitDay | NSCalendarUnitMonth |  NSCalendarUnitYear |NSCalendarUnitSecond | NSCalendarUnitMinute | NSCalendarUnitHour | NSCalendarUnitTimeZone fromDate: [NSDate date]]; // Setup NSDateComponents
[components setTimeZone:[NSTimeZone defaultTimeZone]];
[components setMonth:12];
[components setYear:2014];

// Setup the new date
NSDate *dateToCompare = [gregorianCalendar dateFromComponents: components];

NSLog(@"Ver %@",dateToCompare);

NSUIntegerMax = 18446744073709551615 在位表示中:100000000000000000000000000000000000000000000000000000000000000000000 关闭许多人。