NSDate 1 秒关闭
当我尝试使用日期组件计算经过的时间时,日期相差一秒。这是为什么呢?
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用以下方法将双精度 (NSTimeInterval) 舍入为整数:
长整数“rounded”现在将包含 8。您现在可以将其转换回时间间隔。
并将其与 NSDate 函数一起使用。
因此,要创建仅包含整秒的 NSDate,您可以使用:
或对现有 NSDate 的亚秒进行四舍五入:
You can round a double (NSTimeInterval) to an integer with:
The long integer 'rounded' will now contain 8. You can now cast this back to a time interval.
and use that with the NSDate functions.
So to create an NSDate with only full seconds you can use:
or to round off an existing NSDate's subseconds: