2015-05-15 99 views
0

我有兩個日期按鈕按下設置。這些存儲在從NSObject繼承的自定義對象中。timeIntervalSinceDate報告錯誤的值

屬性:

@property (nonatomic, strong) NSDate *firstDate; 
@property (nonatomic, strong) NSDate *secondDate; 

定製獲取和設置方法:

- (void)setFirstDate:(float)firstDate { 
    _firstDate = [self dateByOmittingSeconds:firstDate]; 
} 

- (void)setSecondDate:(float)secondDate { 
    _secondDate = [self dateByOmittingSeconds:secondDate]; 
} 

- (NSDate *)firstDate { 
    return [self dateByOmittingSeconds:_firstDate]; 
} 

- (NSDate *)secondDate { 
    return [self dateByOmittingSeconds:_secondDate]; 
} 

功能可移除的NSDate的秒部分:

-(NSDate *)dateByOmittingSeconds:(NSDate *)date 
{ 
// Setup an NSCalendar 
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian]; 

// Setup NSDateComponents 
NSDateComponents *components = [gregorianCalendar components: NSUIntegerMax fromDate: date]; 

// Set the seconds 
[components setSecond:00]; 

return [gregorianCalendar dateFromComponents: components]; 
} 

firstDate is 08:00 and secondDate is 13:00,兩者都是今天定的。

我得到兩個日期之間的距離,這樣格式化:

NSString *myString = [self timeFormatted:[currentModel.secondDate timeIntervalSinceDate:currentModel.firstDate]]; 


- (NSString *)timeFormatted:(int)totalSeconds 
{ 

// int seconds = totalSeconds % 60; 
int minutes = (totalSeconds/60) % 60; 
int hours = totalSeconds/3600; 

return [NSString stringWithFormat:@"%luh %lum", (unsigned long)hours, (unsigned long)minutes]; 
} 

但報告4H59米17999.254732秒

有沒有人有這方面的線索?

謝謝!

回答

1

問題不在於timeIntervalSinceDate,而是您的 dateByOmittingSeconds方法不能正確截斷 秒。原因是second不是NSDateComponents中的最小單位。 還有nanosecond,如果你設置一個零和

[components setSecond:0]; 
[components setNanosecond:0]; 

如預期那麼它會工作。

稍微容易的解決方案是使用rangeOfUnit

-(NSDate *)dateByOmittingSeconds:(NSDate *)date 
{ 
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian]; 
    NSDate *result; 
    [gregorianCalendar rangeOfUnit:NSCalendarUnitSecond startDate:&result interval:nil forDate:date]; 
    return result; 
} 
+0

我想出了這個主意我自己,有可能是一個更小的單位,並試圖找到像setMillisecond或相似的,但我找不到它。納秒是我正在尋找的單位 - 現在完美的工作,非常感謝! – Erik