很高兴听到有关如何改进/缩短此方法的建议。总之需要:
以下代码:
- (NSDate*)DateFromNextWeekDay:(NSInteger)weekDay FromDate:(NSDate*)fromDate {
// Returns the next week day, as specified by "weekDay", from the specified "fromDate"
NSDate *fromDateMidday = [[NSDate date] dateBySettingHour:12 andMinute:0];
NSDate *dateCounter = [[fromDateMidday copy] dateByAddingTimeInterval:-86400]; // Take 1 day away, which will get incremented in the loop
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSInteger day;
do{
dateCounter = [dateCounter dateByAddingTimeInterval:86400];
unsigned units = NSWeekdayCalendarUnit;
NSDateComponents *components = [gregorian components:units fromDate:dateCounter];
day = [components weekday];
} while(day != weekDay);
[gregorian release];
return dateCounter;
}
感谢
答案 0 :(得分:3)
您可以找到传递日期的星期几,从星期的目标日减去该值,最后将该结果添加到传入的日期。无需遍历日期。所以它会是:
daysToAdd =(targetDayOfWeek - currentDayDayOfWeek)%7
修改减法的原因是为了处理目标日小于当天的情况(例如星期六,你正在寻找星期二)。