我想創建一個範圍數組,其中包含特定開始日期和結束日期之間的天數。創建日期範圍
例如,我的開始日期爲2012年1月1日,結束日期爲2012年1月7日。數組或範圍應包含NSDate對象(共7個)的集合。
我該怎麼做?
我想創建一個範圍數組,其中包含特定開始日期和結束日期之間的天數。創建日期範圍
例如,我的開始日期爲2012年1月1日,結束日期爲2012年1月7日。數組或範圍應包含NSDate對象(共7個)的集合。
我該怎麼做?
NSCalendar是有幫助這裏,因爲它知道有關日期的日曆。所以,通過使用下面的代碼(假設你有startDate和endData,並且你希望包含在列表中),你可以遍歷日期,添加一天(NSCalendar將負責包裝月份和閏年,等等)。
NSMutableArray *dateList = [NSMutableArray array];
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:1];
[dateList addObject: startDate];
NSDate *currentDate = startDate;
// add one the first time through, so that we can use NSOrderedAscending (prevents millisecond infinite loop)
currentDate = [currentCalendar dateByAddingComponents:comps toDate:currentDate options:0];
while ([endDate compare: currentDate] != NSOrderedAscending) {
[dateList addObject: currentDate];
currentDate = [currentCalendar dateByAddingComponents:comps toDate:currentDate options:0];
}
[comps release];
只需創建它們,並將它們添加到一個數組...
NSMutableArray *arr = [NSMutableArray array];
NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
[comps setMonth:1];
[comps setYear:2012];
for(int i=1;i<=7;i++) {
[comps setDay:i];
[arr addObject:[[NSCalendar currentCalendar] dateFromComponents:comps]];
}
從蘋果DOC: 要計算日期序列,使用enumerateDatesStartingAfterDate:matchingComponents:選擇:usingBlock:方法,而不是調用此方法的 - 在一個循環( nextDateAfterDate: matchingComponents:選項)前面的循環迭代的結果。
隨着我,它會遍歷所有以「matchingComponents」,直到你完成與迭代「stop.memory =真正的」
let calendar = NSCalendar.currentCalendar()
let startDate = calendar.startOfDayForDate(NSDate())
let finishDate = calendar.dateByAddingUnit(.Day, value: 10, toDate: startDate, options: [])
let dayComponent = NSDateComponents()
dayComponent.hour = 1
calendar.enumerateDatesStartingAfterDate(startDate, matchingComponents: dayComponent, options: [.MatchStrictly]) { (date, exactMatch, stop) in
print(date)
if date!.compare(finishDate!) == NSComparisonResult.OrderedDescending {
// .memory gets at the value of an UnsafeMutablePointer
stop.memory = true
}
}
歡迎來到SO :)請不要**只是發佈代碼塊作爲答案,但也給一點解釋,以提高您的答案的質量。 – 2016-07-05 21:59:21
謝謝匹配所有的日期,我想這就是我一直在尋找。然而while循環中的條件總是返回true。 '(LLDB)PO endDate' '(的NSDate *)$ 6 = 0x06b9cc60 2012-03-11 0時12分42秒+ 0000' '(LLDB)PO currentDate' '(的NSDate *)$ J = 0x06b9dd20 2012- 03-11 00:12:42 + 0000' 但是返回值仍然是真的。 – joostevilghost 2012-03-11 07:58:54
我猜你運行startDate = [NSDate日期]和endDate = [NSDate日期],這導致兩個日期不相同,但非常相似(關幾毫秒)。我已經對此進行了修改,以便對此情況很安全,但如果您使用的是日期選擇器,則可能不會造成問題,因爲日期將手動設置爲00:00:00.0,而不是00:12 :42.xx和00:12:42.yy – gaige 2012-03-11 10:29:27
這很好,但我遇到了一個問題,我在11月份錯過了結束日期。原來是夏令時。將此添加到您的NSCalendar聲明中以避免出現'[currentCalendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@「GMT」]]; //忽略夏令時 – smokingoyster 2012-08-09 18:31:08