timeIntervalSinceDate报告错误的值

时间:2015-05-15 17:16:51

标签: ios objective-c nsdate nstimeinterval

我有两个日期是按下按钮设置的。它们存储在一个继承自NSObject的自定义对象中。

属性:

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

自定义getter和setter方法:

- (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 08:00 ,secondDate 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];
}

但它报告 4h 59m 17999.254732秒

有没有人知道为什么会这样?

谢谢!

1 个答案:

答案 0 :(得分: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;
}