The logic for my problem is a mouthful and I have already come up with a solution. My solution is posted below. I am looking to see if someone can come up with a more efficient / simpler solution.
The method is supposed to return the next, future from now, occurring weekday given a date. Time should be preserved between the input date and the output date.
For all examples, today is Friday May 8, 2015, 4:00 PM: All inputs and outputs are in 2015:
+---------------------------+---------------------------+
| Input | Output |
+---------------------------+---------------------------+
| Tuesday April 7, 3:00 PM | Monday May 11, 3:00 PM |
| Thursday May 7, 3:00 PM | Monday May 11, 3:00 PM |
| Thursday May 7, 5:00 PM | Friday May 8, 5:00 PM |
| Tuesday May 12, 3:00 PM | Wednesday May 13, 3:00 PM |
| Saturday June 20, 3:00 PM | Monday June 22, 3:00 PM |
+---------------------------+---------------------------+
Here is some pseudo code for the logic:
do {
date += 1 day;
} while(date.isWeekend || date.isInThePast)
Here is the solution I came up with, avoiding the use of loops to keep efficiency in mind:
- (NSDate *)nextWeekDayInFuture {
NSDate *now = [NSDate date];
NSDate *nextWeekDaydate;
NSCalendar *calendar = [NSCalendar currentCalendar];
nextWeekDaydate = [self dateByAddingDays:1]; // custom method, adds 1 day
if ([nextWeekDaydate isLessThan:now]) {
NSDateComponents *nowComponents = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:now];
NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:nextWeekDaydate];
[nowComponents setHour:dateComponents.hour];
[nowComponents setMinute:dateComponents.minute];
[nowComponents setSecond:dateComponents.second];
nextWeekDaydate = [calendar dateFromComponents:nowComponents];
if ([nextWeekDaydate isLessThan:now]) {
nextWeekDaydate = [nextWeekDaydate dateByAddingDays:1];
}
}
NSDateComponents *components = [calendar components:NSCalendarUnitWeekday fromDate:nextWeekDaydate];
if (components.weekday == Saturday) {
nextWeekDaydate = [nextWeekDaydate dateByAddingDays:2];
} else if (components.weekday == Sunday) {
nextWeekDaydate = [nextWeekDaydate dateByAddingDays:1];
}
return nextWeekDaydate;
}
Use the input / output table from above to test your logic before posting a solution.