Given a reference date I need to find the following say ‘Wednesday’.
Just to be clear, if the reference date is say Tuesday then it should return the Wednesday from the same week.
If the reference date is Wednesday or later then it needs to return the following Wednesday from the next week.
It’s important that it does not return a Wednesday past the reference date.
I’ve been looking at using NSDateComponents but not sure how to get the following day of the week that must always be in the future.
This is what I have so far:
NSDate *referenceDate = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:referenceDate];
[dateComponents setWeekday:4]; // Wednesday
NSDate *followingWednesday = [calendar dateFromComponents:dateComponents];
Though this code does not make the distinction between Wednesday past in the same week or the following Wednesday, and hear lies my problem.
I know I could generate two dates one from current week and one from the next week and then use an if statement to check which one is in the future but this seems like a lot of code to do a simple thing.
Is there a better way?
Any help would be appreciated.
Update
It seems that setting the weekday does not actually affect the date returned by the dateComponents: method of NSCalendar. My example code above returns the same date regardless of what is set for the weekday.
So now I’m more stumped.
I would do it like this: