Domanda

Sarebbe felice di sentire i suggerimenti su come migliorare / accorciare questo metodo. In breve bisogno di:

  • Trova la data successiva per la quale è il giorno della settimana (ad es. Mer) corrisponde a ciò che viene passato nel metodo.
  • Ad esempio il prossimo mercoledì da una data data (e inclusa quella data data)

Codice di seguito:

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

Grazie

È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top