2017-12-03 43 views
0

我使用NSDateComponents分別獲取每日,每月,每年,每小時,每分鐘等,但日,月,年和秒不準確2017年11月08日1:00:00 ....有人知道我錯過了什麼嗎?NSDateComponents不打印準確的日/月/年時間

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
     [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"]; 
     NSDate *date = [dateFormatter dateFromString:@"2017-11-08 1:00:00"]; 
     NSCalendar *calendar = [NSCalendar currentCalendar]; 
     NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date]; 
     NSInteger day = [components day]; 
     NSInteger month = [components month]; 
     NSInteger year = [components year]; 
     NSInteger hour = [components hour]; 
     NSInteger minute = [components minute]; 
     NSInteger second = [components second]; 
     NSLog(@"day: %ld",(long)day); 
     NSLog(@"month: %ld",(long)month); 
     NSLog(@"year: %ld",(long)year); 
     NSLog(@"hour: %ld",(long)hour); 
     NSLog(@"minute: %ld",(long)minute); 
     NSLog(@"second: %ld",(long)second); 

輸出:

 day: 2147483647 
     month: 2147483647 
     year: 2147483647 
     hour: 1 
     minute: 0 
     second: 2147483647 

回答

2

你只是得到小時和分鐘,因爲這是所有你問的。如果你真的要求日,月,年和秒,你會得到它們:

NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | 
         NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond; 
NSDateComponents *components = [calendar components:units fromDate:date]; 
相關問題