2011-09-28 140 views
1

如何獲取兩個日期之間的所有日期?獲取兩個NSDates之間的所有日期(不是幾天)

例如: 開始日期= 2011/01/25 結束日期= 2011/02/03

+2

你是什麼意思日期,而不是天? – msgambel

+0

可能重複[兩個NSDates之間的天數](http://stackoverflow.com/questions/4739483/number-of-days-between-two-nsdates) –

+0

@JoshCaswell主題說:「不是天」他想要一個日期列表。 –

回答

2

NSCalendarUnit供應定義拍攝日期是標準化的護理日期&之間的步驟。

的iOS API 8,雨燕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 
    } 
+1

謝謝。我正在使用這個Objective-C版本來完成我的場景。 – kevinl

0

找到兩個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]; 
    } 
} 
相關問題