[英]Get all NSDates BETWEEN startDate and endDate
My question is the REVERSE of the typical "How do I find out if an NSDate is between startDate and endDate?" 我的问题是典型的“如何判断NSDate是否在startDate和endDate之间?”的反转?
What I want to do is find ALL NSDATES (to the day, not hour or minute) that occur BETWEEN startDate and endDate. 我想要做的是找到在startWate和endDate之间发生的所有NSDATES(到当天,而不是小时或分钟)。 Inclusive of those dates would be preferable, although not necessary.
包括这些日期将是可取的,尽管没有必要。
Example: (I know that these don't represent NSDates, these are just for illustration) 示例:(我知道这些不代表NSDates,这些只是为了说明)
INPUT: startDate = 6/23/10 20:11:30 endDate = 6/27/10 02:15:00 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 输出: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.
只是我不知道在制作高效代码方面从哪里开始,而不必一点一点地逐步完成NSDates。
Use an NSCalendar
instance to convert your start NSDate
instance into an NSDateComponents
instance, add 1 day to the NSDateComponents
and use the NSCalendar
to convert that back to an NSDate
instance. 使用一个
NSCalendar
实例添加到开始转换NSDate
实例为NSDateComponents
情况下,每天1次添加到NSDateComponents
并使用NSCalendar
将其转换回一个NSDate
实例。 Repeat the last two steps until you reach your end date. 重复最后两个步骤,直到达到结束日期。
Add 24 hours to the start date until you go past the end date. 添加24小时到开始日期,直到超过结束日期。
for ( nextDate = startDate ; [nextDate compare:endDate] < 0 ; nextDate = [nextDate addTimeInterval:24*60*60] ) {
// use date
}
You could round the first date to noon or midnight before starting the loop if you care about the time of day. 如果您关心一天中的时间,您可以在开始循环之前将第一个日期舍入到中午或午夜。
Ever since OS X 10.9 and iOS 8.0 there is the following very clean way to do this. 从OS X 10.9和iOS 8.0开始,有以下非常简洁的方法。 It also deals with end of month jumps.
它还涉及月末跳跃。
let cal = NSCalendar.currentCalendar()
let start = NSDate()
let end = // some end date
var next = start
while !cal.isDate(next, inSameDayAsDate: end) {
next = cal.dateByAddingUnit(.Day, value: 1, toDate: next, options: [])!
// do something with `next`
}
Note that for older OS versions -isDate:inSameDayAsDate:
can be replaced by some call to eg -components:fromDate:toDate:options:
and -dateByAddingUnit:value:toDate:options:
can be replaced by dateByAddingComponents:toDate:options:
. 请注意,对于较旧的OS版本
-isDate:inSameDayAsDate:
可以通过调用例如-isDate:inSameDayAsDate:
来替换-components:fromDate:toDate:options:
和-dateByAddingUnit:value:toDate:options:
可以替换为dateByAddingComponents:toDate:options:
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.