开发者

how can I improve this "DateFromNextWeekDay:FromDate" method code?

Would be happy to hear of suggestions re how to improve / shorten this method. In short needing to:

  • Find the next date for which it's day of week (e.g. Wed) matches what is passed into the method.
  • For example the next WED from a given date (and including that given date)

Code Below:

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

thanks


You could just find the day of the week of the passed in date, subtract that from the target day of the week, and finally add that result to the date passed in. No need to loop through the dates. So it would be:

daysToAdd = ( targetDayOfWeek - currentDayDayOfWeek ) % 7

The reason for moding the subtraction is to handle the cases where the target day is smaller than the current day (it is a saturday and you are looking for a tuesday for example).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜