1

How can I get all the dates that come in between 2 dates?

For example: Start date = 2011/01/25 End date = 2011/02/03

Black Frog
  • 11,595
  • 1
  • 35
  • 66
iOSDev
  • 3,617
  • 10
  • 51
  • 91
  • 2
    What do you mean by dates, and not days? – msgambel Sep 28 '11 at 04:45
  • possible duplicate of [Number of days between two NSDates](http://stackoverflow.com/questions/4739483/number-of-days-between-two-nsdates) – jscs Sep 28 '11 at 05:58
  • @JoshCaswell the subject said "Not days" He want a listing of dates. – Black Frog Sep 28 '11 at 07:47
  • @Black Frog: But imMobile has not bothered to indicate _at what interval_. `NSTimeInterval` is a `double`, with millisecond resolution. There are literally millions of "dates" in between any two. – jscs Sep 28 '11 at 07:51
  • Yes, each millisecond is a different date in "Time & Space" but I believe he wants each day as 24 hour period. – Black Frog Sep 28 '11 at 14:20

3 Answers3

2

NSCalendarUnit serves for defining the step between the dates & taking care of the dates being normalized.

iOS 8 API, Swift 2.0

    func generateDates(calendarUnit: NSCalendarUnit, startDate: NSDate, endDate: NSDate) -> [NSDate] {

            let calendar = NSCalendar.currentCalendar()
            let normalizedStartDate = calendar.startOfDayForDate(startDate)
            let normalizedEndDate = calendar.startOfDayForDate(endDate)

            var dates = [normalizedStartDate]
            var currentDate = normalizedStartDate

            repeat {

                currentDate = calendar.dateByAddingUnit(calendarUnit, value: 1, toDate: currentDate, options: NSCalendarOptions.MatchNextTime)!
                dates.append(currentDate)

            } while !calendar.isDate(currentDate, inSameDayAsDate: normalizedEndDate)

            return dates
    }
Kex
  • 776
  • 10
  • 22
2

1) Find the no of days between two dates. Then,

for(i=0;i<noofdays;i++)
{
//Find the next date
//add to the array
}

To find number of days

To find next date

Community
  • 1
  • 1
KingofBliss
  • 15,055
  • 6
  • 50
  • 72
0

To find all days between two NSDates:

- (void)cerateDaysArray{
    _daysArray = [NSMutableArray new];
    NSCalendar *calendar = [[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];
    [calendar setTimeZone:[NSTimeZone systemTimeZone]];
    NSDate *startDate = [_minDate copy];
    NSDateComponents *deltaDays = [NSDateComponents new];
    [deltaDays setDay:1];
    [_daysArray addObject:startDate];
    while ([startDate compare:_maxDate] == NSOrderedAscending) {
       startDate = [calendar dateByAddingComponents:deltaDays toDate:startDate options:0];
       [_daysArray addObject:startDate];
   }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Mike.R
  • 2,824
  • 2
  • 26
  • 34