获取 startDate 和 endDate 之间的所有 NSDate
我的问题是典型的“如何确定 NSDate 是否在 startDate 和 endDate 之间?”的反面。
我想要做的是找到 startDate 和 endDate 之间发生的所有 NSDATES(到天,而不是小时或分钟)。最好包括这些日期,尽管不是必需的。
例子: (我知道这些并不代表 NSDate,这些只是为了说明)
输入: 开始日期 = 6/23/10 20:11:30 结束日期 = 6/27/10 02:15:00
输出: NSArray of: 6/23/10, 6/24/10, 6/25/10, 6/26/10, 6/27/10
我不介意做这项工作。只是我不知道从哪里开始编写高效的代码,而不必一点点地逐步完成 NSDates。
My question is the REVERSE of the typical "How do I find out if an NSDate is between startDate and endDate?"
What I want to do is find ALL NSDATES (to the day, not hour or minute) that occur BETWEEN startDate and endDate. Inclusive of those dates would be preferable, although not necessary.
Example:
(I know that these don't represent NSDates, these are just for illustration)
INPUT:
startDate = 6/23/10 20:11:30
endDate = 6/27/10 02:15:00
OUTPUT:
NSArray of: 6/23/10, 6/24/10, 6/25/10, 6/26/10, 6/27/10
I don't mind doing the work. It's just that I don't know where to start in terms of making efficient code, without having to step through the NSDates little by little.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
NSCalendar
实例将起始NSDate
实例转换为NSDateComponents
实例,向NSDateComponents
添加 1 天,并使用 NSCalendar 将其转换回 NSDate 实例。重复最后两个步骤,直到到达结束日期。Use an
NSCalendar
instance to convert your startNSDate
instance into anNSDateComponents
instance, add 1 day to theNSDateComponents
and use theNSCalendar
to convert that back to anNSDate
instance. Repeat the last two steps until you reach your end date.在开始日期上添加 24 小时,直到超过结束日期。
如果您关心一天中的时间,则可以在开始循环之前将第一个日期舍入到中午或午夜。
Add 24 hours to the start date until you go past the end date.
You could round the first date to noon or midnight before starting the loop if you care about the time of day.
自 OS X 10.9 和 iOS 8.0 以来,有以下非常干净的方法可以做到这一点。它还处理月末跳跃。
请注意,对于较旧的操作系统版本,
-isDate:inSameDayAsDate:
可以替换为对例如-components:fromDate:toDate:options:
和-dateByAddingUnit:value 的某些调用:toDate:options:
可以替换为dateByAddingComponents:toDate:options:
。Ever since OS X 10.9 and iOS 8.0 there is the following very clean way to do this. It also deals with end of month jumps.
Note that for older OS versions
-isDate:inSameDayAsDate:
can be replaced by some call to e.g.-components:fromDate:toDate:options:
and-dateByAddingUnit:value:toDate:options:
can be replaced bydateByAddingComponents:toDate:options:
.