0
比較兩個日期(currentDate
和_timerStartDate
)後,我得到以下輸出獲得意想不到的輸出NSDateComponents
nstimeinterval: 88.998212
2014-05-14 14:07:08.284 currentDate: 14-05-2014 14:07:08
2014-05-14 14:07:08.284 stopDate: 14-05-2014 14:05:39
2014-05-14 14:07:08.284 hour: 10
這是正確的和預期。然而,當我打破timerDate
下來,我從NSLog得到10個小時......我期待着零。我究竟做錯了什麼?
這裏是我的代碼:
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:_timerStartDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm:ss"];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
NSLog(@"nstimeinterval: %f", timeInterval);
[dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
NSLog(@"currentDate: %@", [dateFormatter stringFromDate:currentDate]);
NSLog(@"stopDate: %@", [dateFormatter stringFromDate:_timerStartDate]);
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components: (NSHourCalendarUnit | NSYearCalendarUnit) fromDate:timerDate];
NSLog(@"year: %li", (long)components.year);
NSLog(@"timer: %@", timeString);
timerTicksForCounter = timeString;
NSLog(@"hour: %li", (long)components.hour);
您似乎對這些API中某些API的意圖感到困惑。如果你想要量化兩個日期之間的差異,你可以使用'components:fromDate:toDate:options:'method,a la:[[calendar components:NSCalendarUnitHour fromDate:_timerStartDate toDate:currentDate options:0];' – warrenm