【发布时间】:2012-03-10 23:52:30
【问题描述】:
我想创建一个范围数组,其中包含特定开始日期和结束日期之间的天数。
例如,我的开始日期为 2012 年 1 月 1 日,结束日期为 2012 年 1 月 7 日。数组或范围应包含 NSDate 对象的集合(总共 7 个)。
我该怎么做?
【问题讨论】:
标签: objective-c nsdate foundation
我想创建一个范围数组,其中包含特定开始日期和结束日期之间的天数。
例如,我的开始日期为 2012 年 1 月 1 日,结束日期为 2012 年 1 月 7 日。数组或范围应包含 NSDate 对象的集合(总共 7 个)。
我该怎么做?
【问题讨论】:
标签: objective-c nsdate foundation
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];
【讨论】:
(lldb) po endDate(NSDate *) $6 = 0x06b9cc60 2012-03-11 00:12:42 +0000(lldb) po currentDate(NSDate *) $7 = 0x06b9dd20 2012-03-11 00:12:42 +0000但是返回值还是true。
[currentCalendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]]; // ignore daylight savings
只需创建它们并将它们添加到数组中...
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]];
}
【讨论】:
来自苹果文档: 要计算日期序列,请使用 enumerateDatesStartingAfterDate:matchingComponents:options:usingBlock: 方法而不是调用此方法 ( - nextDateAfterDate:matchingComponents:options: ) 在与前一个循环迭代的结果的循环中。
如我所见,它将迭代所有与“matchingComponents”匹配的日期,直到您使用“stop.memory = true”完成迭代
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
}
}
【讨论】: