如何改进这个“DateFromNextWeekDay:FromDate”方法代码?

时间:2011-03-20 23:42:35

标签: iphone objective-c ios nsdate nsdatecomponents

很高兴听到有关如何改进/缩短此方法的建议。总之需要:

  • 查找下一个日期(例如星期三)与传递给方法的日期相匹配。
  • 例如,给定日期(包括该给定日期)的下一个WED

以下代码:

- (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;
}

感谢

1 个答案:

答案 0 :(得分:3)

您可以找到传递日期的星期几,从星期的目标日减去该值,最后将该结果添加到传入的日期。无需遍历日期。所以它会是:

daysToAdd =(targetDayOfWeek - currentDayDayOfWeek)%7

修改减法的原因是为了处理目标日小于当天的情况(例如星期六,你正在寻找星期二)。