NSDate 1 秒关闭

发布于 2024-12-13 09:11:46 字数 603 浏览 4 评论 0原文

当我尝试使用日期组件计算经过的时间时,日期相差一秒。这是为什么呢?

NSCalendar *sysCalendar = [NSCalendar currentCalendar];
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *conversionInfo = [sysCalendar components:unitFlags fromDate:timeStarted toDate:[[NSDate date]addTimeInterval:+1.0] options:0];
timeElapsed = [sysCalendar dateFromComponents:conversionInfo];

我的临时解决方案是增加一秒钟,但我想了解为什么会发生这种情况或者是否有更好的解决方案。

编辑:不是一秒差,而是向下舍入。当我得到以秒为单位的时间间隔(将其精确到小数位)时,结果为 1.9、2.9、3.9,并分别显示 00:00:01、00:00:02、00:00:03。我怎样才能让它四舍五入?

When I try to calculate the time elapsed using Date Components the date is one second off. Why is this?

NSCalendar *sysCalendar = [NSCalendar currentCalendar];
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *conversionInfo = [sysCalendar components:unitFlags fromDate:timeStarted toDate:[[NSDate date]addTimeInterval:+1.0] options:0];
timeElapsed = [sysCalendar dateFromComponents:conversionInfo];

My temporary fix is to add one second, but I want to understand why it is happening or if there is a better fix.

EDIT: It is not one second off, but it is rounding down. When I get the time interval in seconds (which brings it down to decimal places) it comes out to be 1.9, 2.9, 3.9 and is showing 00:00:01, 00:00:02, 00:00:03 respectively. How can I get it to round up?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

等你爱我 2024-12-20 09:11:46

您可以使用以下方法将双精度 (NSTimeInterval) 舍入为整数:

NSTimeInterval unrounded = 7.8;
long rounded = lround(unrounded);

长整数“rounded”现在将包含 8。您现在可以将其转换回时间间隔。

NSTimeInterval roundedTimeInterval = (NSTimeInterval)rounded;

并将其与 NSDate 函数一起使用。

因此,要创建仅包含整秒的 NSDate,您可以使用:

NSDate *nowEnough = [NSDate dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)lround([NSDate timeIntervalSinceReferenceDate])];

或对现有 NSDate 的亚秒进行四舍五入:

NSDate *thenEnough = [NSDate dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)lround([existingNSDatesName timeIntervalSinceReferenceDate])];

You can round a double (NSTimeInterval) to an integer with:

NSTimeInterval unrounded = 7.8;
long rounded = lround(unrounded);

The long integer 'rounded' will now contain 8. You can now cast this back to a time interval.

NSTimeInterval roundedTimeInterval = (NSTimeInterval)rounded;

and use that with the NSDate functions.

So to create an NSDate with only full seconds you can use:

NSDate *nowEnough = [NSDate dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)lround([NSDate timeIntervalSinceReferenceDate])];

or to round off an existing NSDate's subseconds:

NSDate *thenEnough = [NSDate dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)lround([existingNSDatesName timeIntervalSinceReferenceDate])];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文