iOSDev
iOSDev

Reputation: 3617

Get all dates (not days) between two NSDates

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

Upvotes: 1

Views: 2158

Answers (3)

Mike.R
Mike.R

Reputation: 2938

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];
   }
}

Upvotes: 0

Kex
Kex

Reputation: 776

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
    }

Upvotes: 2

KingofBliss
KingofBliss

Reputation: 15115

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

Upvotes: 2

Related Questions