سؤال

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).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top