nextdatematchingday objective-c method - there better way code i've got?
- (nsdate*)nextdatematchingday:(nsdatecomponents*)daytime { // find next date (including date & time) current date, which: // (a) dayofweek(no time) matches dayofweek input "datetime" nsdatecomponents // (b) date > currentdatetime // (c) final date time based on time passed in "datetime" nsdatecomponents // e.g. daytime=sun10am's, currentdate=sun1st2pm => result=sun8th10am // e.g. daytime=sun10am's, currentdate=sun1st9am => result=sun1st10am // e.g. daytime=sun10am's, currentdate=fri1st1pm => result=sun8th10am // prepare nsdate *currdate = [nsdate date]; nscalendar *gregorian = [[nscalendar alloc] initwithcalendaridentifier:nsgregoriancalendar]; nsdatecomponents *addcomps = [[[nsdatecomponents alloc] init] autorelease]; unsigned unitflags = nsyearcalendarunit | nsmonthcalendarunit | nsdaycalendarunit; nsdatecomponents* currcomps = [gregorian components:unitflags fromdate:currdate]; nsinteger dayscounter = 0; { [addcomps setday:dayscounter]; nsdate *futuredate = [gregorian datebyaddingcomponents:addcomps todate:currdate options:0]; nsdatecomponents* futurecomps = [gregorian components:unitflags fromdate:futuredate]; if ( [futurecomps day] == [currcomps day] && [futurecomps month] == [currcomps month] && [futurecomps year] == [currcomps year] ) return futuredate; dayscounter++; } while (dayscounter < 10); // double check return nil; // double check - should not }
this seems improvement - not sure if there's still way condense down further though?
+ (nsdate*)nextdatematchingday:(nsdatecomponents*)daytime sourcedate:(nsdate*)sourcedate { // find next date (including date & time) current date, which: // (a) dayofweek(no time) matches dayofweek input "datetime" nsdatecomponents // (b) date > currentdatetime // (c) final date time based on time passed in "datetime" nsdatecomponents // e.g. daytime=sun10am's, currentdate=sun1st2pm => result=sun8th10am // e.g. daytime=sun10am's, currentdate=sun1st9am => result=sun1st10am // e.g. daytime=sun10am's, currentdate=fri1st1pm => result=sun8th10am nsdate *returndate = [sourcedate datewithhoursminssecscomps:daytime]; // check if same day nsinteger configdow = [daytime weekday]; nsinteger sourcedow = [sourcedate dayofweek]; if ( configdow == sourcedow ) { // source date correct day - before or after if ( [returndate isbeforethisdate:sourcedate] ) { // can't source date - move forward 7 days returndate = [returndate datebyaddingdays:7]; return returndate; } else { // can source date (with new time) return returndate; } } // source day on day-of-week other daytime provided value nsinteger dayofweekdiff = (7 + (configdow - sourcedow)) % 7; returndate = [returndate datebyaddingdays:dayofweekdiff]; return returndate; }
Comments
Post a Comment