gpt4 book ai didi

ios - timeIntervalSinceDate 报告错误值

转载 作者:行者123 更新时间:2023-11-29 02:01:52 24 4
gpt4 key购买 nike

我有两个通过按下按钮设置的日期。这些存储在继承自 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];
}

第一个日期是08:00,第二个日期是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 秒

有人知道这是为什么吗?

谢谢!

最佳答案

问题不是 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;
}

关于ios - timeIntervalSinceDate 报告错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30265239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com