如何将当前日期(或任何日期)创建为没有小时、分钟和秒的 NSDate?
我需要创建当前日期(或任何 NSDate)的 NSDate
,不带小时、分钟和秒,并将其保留为 NSDate
,只需几行可能的?
我需要对日期进行一些计算,并且小时、分钟和秒会引起问题,我需要绝对日期(我希望绝对是正确的短语)。它适用于 iPhone 应用程序。
我正在使用 [NSDate date]
创建日期,其中添加了小时、分钟和秒。另外,我还为日期添加了月份,我认为这可以满足夏令时的要求,因为在某些日期我有 2300 小时。
因此,理想情况下,我需要一个函数来从 NSDates 创建绝对 NSDates。
我知道我之前问过类似的问题,但我需要最终得到 NSDate 而不是字符串,而且我有点担心指定日期格式,例如 yyyy 等。
I need to create an NSDate
of the current date (or on any NSDate) without the hours, minutes and seconds and keep it as an NSDate
, in as few lines of as possible?
I need to perform some calculations on dates and having hours, minutes and seconds cause problems, I need absolute dates (I hope absolute is the right phrase). Its for an iPhone app.
I'm creating dates with [NSDate date]
which add hours, minutes and seconds. Also I'm adding months to dates which I think caters for day light savings as I get 2300 hours on some dates.
So ideally I need a function to create absolute NSDates from NSDates.
I know I asked a similar question earlier, but I need to end up with NSDate not a string and I'm a little concerned about specifying a date format e.g. yyyy etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您必须了解,即使从
NSDate
中删除小时、分钟和秒,它仍然代表单个时刻。您永远不会得到像2011-01-28
这样代表一整天的NSDate
;它将始终为2011-01-28 00:00:00 +00:00
。这意味着您还必须考虑时区。下面是一个方法(作为
NSDate
类别实现),它在 UTC 午夜与self
同一天返回一个NSDate
:First, you have to understand that even if you strip hours, minutes and seconds from an
NSDate
, it will still represent a single moment in time. You will never get anNSDate
to represent an entire day like2011-01-28
; it will always be2011-01-28 00:00:00 +00:00
. That implies that you have to take time zones into account, as well.Here is a method (to be implemented as an
NSDate
category) that returns anNSDate
at midnight UTC on the same day asself
: