Get all NSDates BETWEEN startDate and endDate

My question is the REVERSE of the typical "How do I know if NSDate is between startDate and endDate?"

What I want to do is find ALL NSDATES (per day, not hour or minute) that happen BETWEEN startDate and endDate. The inclusion of these dates would be preferable, although this was not necessary.

Example: (I know that they do not represent NSDates, this is for illustration only)

INPUT: startDate = 6/23/10 20:11:30 endDate = 6/27/10 02:15:00

CONCLUSION: NSArray from: 6/23/10, 6/24/10, 6/25/10, 6/26/10, 6/27/10

I don't mind doing the job. It’s just that I don’t know where to start from the point of view of creating efficient code, without the need to gradually change NSDates.

+6
objective-c iphone nsdate
source share
3 answers

Add 24 hours to the start date until you finish the end date.

for ( nextDate = startDate ; [nextDate compare:endDate] < 0 ; nextDate = [nextDate addTimeInterval:24*60*60] ) { // use date } 

You can get around your first date at noon or midnight before starting the cycle if you care about the time of day.

+5
source share

Use an NSCalendar instance to convert the start NSDate instance to an NSDateComponents instance, add 1 day to NSDateComponents and use NSCalendar to convert this instance to an NSDate instance. Repeat the last two steps until you reach the end date.

+9
source share

Since the advent of OS X 10.9 and iOS 8.0, there is the following very clean way to do this. It also applies to jumping at the end of the month.

 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 versions of the OS, -isDate:inSameDayAsDate: can be replaced by some call, for example. -components:fromDate:toDate:options: and -dateByAddingUnit:value:toDate:options: can be replaced with dateByAddingComponents:toDate:options:

+2
source share

All Articles