如何为NSDate设置秒为零 [英] How to set seconds to zero for NSDate

查看:103
本文介绍了如何为NSDate设置秒为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从 UIDatePicker 获得 NSDate ,但它不断返回一个日期时间尾随20秒。如何手动将 NSDate 的第二个设为零?

I'm trying to get NSDate from UIDatePicker, but it constantly returns me a date time with trailing 20 seconds. How can I manually set NSDate's second to zero?

推荐答案

NSDate是不可变的,所以你不能修改它的时间。但是您可以创建一个新的日期对象,该对象捕捉到最近的分钟:

NSDate is immutable, so you cannot modify its time. But you can create a new date object that snaps to the nearest minute:

NSTimeInterval time = floor([date timeIntervalSinceReferenceDate] / 60.0) * 60.0;
NSDate *minute = [NSDate dateWithTimeIntervalSinceReferenceDate:time];

编辑以回答Uli的评论

NSDate 的参考日期是2001年1月1日0:00 GMT。从那时起,已经添加了两个闰秒:2005和2010,因此 [NSDate timeIntervalSinceReferenceDate] 返回的值应该关闭两秒。

The reference date for NSDate is January 1, 2001, 0:00 GMT. There have been two leap seconds added since then: 2005 and 2010, so the value returned by [NSDate timeIntervalSinceReferenceDate] should be off by two seconds.

事实并非如此: timeIntervalSinceReferenceDate 与墙面时间完全同步。

This is not the case: timeIntervalSinceReferenceDate is exactly synchronous to the wall time.

当回答这个问题时,我没有确保这是真的。我只是假设Mac OS会表现为UNIX时间(1970年代):POSIX保证每天从86,400秒的倍数开始。

When answering the question I did not make sure that this is actually true. I just assumed that Mac OS would behave as UNIX time (1970 epoch) does: POSIX guarantees that each day starts at a multiple of 86,400 seconds.

查看从 NSDate 返回的值,这个假设似乎是正确,但肯定会很高兴找到一个明确的(文件)的声明。

Looking at the values returned from NSDate this assumption seems to be correct but it sure would be nice to find a definite (documented) statement of that.

这篇关于如何为NSDate设置秒为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆