【问题标题】:timeIntervalSinceDate reporting wrong valuetimeIntervalSinceDate 报告错误值
【发布时间】:2015-07-27 17:12:07
【问题描述】:

我有两个通过按钮设置的日期。这些存储在一个继承自 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 59m17999.254732 秒

有人知道这是为什么吗?

谢谢!

【问题讨论】:

    标签: ios objective-c nsdate nstimeinterval


    【解决方案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;
    }
    

    【讨论】:

    • 我自己想出了一个想法,可能有一个更小的单位,并试图找到像 setMillisecond 或类似的东西,但我找不到它。纳秒是我一直在寻找的单位 - 现在完美运行,非常感谢!
    猜你喜欢
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多