2015-05-25 21 views
-1

我試圖[NSDate的日期],但功能dateFromComponents返回錯誤值的月和年設置,這是我的代碼: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年,這是爲什麼?

謝謝!

回答

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 在比特表示:10000000000000000000000000000000000000000000000000000000000000000 要多關閉。