开发者

Get all dates (not days) between two NSDates

开发者 https://www.devze.com 2023-04-08 17:30 出处:网络
How can I get all the dates that come in between 2 date开发者_如何学运维s? For example: Start date = 2011/01/25

How can I get all the dates that come in between 2 date开发者_如何学运维s?

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


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


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
    }


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

精彩评论

暂无评论...
验证码 换一张
取 消