例如:
原始日期:23/03/2012 间隔:每 2 周
输出:最近发生 -> 06/04/2012
如何在 Objective-C (iOS) 中以最佳方式实现这一目标?
旁注:我目前的工作不太好而且非常糟糕的解决方案:
+ (NSDate *) getRelativeStartDateForIntervalType:(NSInteger)intervalType andStartDateTime:(NSDate *)startDateTime {
NSDateComponents *components = [[NSDateComponents alloc] init];
BOOL found = false;
NSDate *relativeStartDate;
NSDate *previousDate;
for (int i = 0; !found ; i++) {
previousDate = relativeStartDate;
switch (intervalType) {
case 0:
[components setDay:i]; // add i days
break;
case 1:
[components setWeek:i]; // add i weeks
break;
case 2:
[components setMonth:i]; // add i months
break;
case 3:
[components setDay:i]; // add i weeks
break;
default:
NSLog(@"you shouldn't be here");
break;
}
relativeStartDate = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:startDateTime options:0];
if ([relativeStartDate compare:[NSDate date]] == NSOrderedDescending) {
found = true;
if (i > 0 && [previousDate compare:[NSDate date]] == NSOrderedDescending) {
relativeStartDate = previousDate;
}
}
}
return relativeStartDate;
}