Note that there are some explanatory texts on larger screens.

plurals
  1. POGet an NSDate for a following day of week from a reference NSDate?
    primarykey
    data
    text
    <p>Given a reference date I need to find the following say 'Wednesday'.</p> <p>Just to be clear, if the reference date is say Tuesday then it should return the Wednesday from the <strong>same</strong> week. </p> <p>If the reference date is Wednesday or later then it needs to return the following Wednesday from the <strong>next</strong> week.</p> <p>It's important that it does not return a Wednesday past the reference date.</p> <p>I've been looking at using <code>NSDateComponents</code> but not sure how to get the following day of the week that must always be in the future.</p> <p>This is what I have so far:</p> <pre><code>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]; </code></pre> <p>Though this code does not make the distinction between Wednesday past in the same week or the following Wednesday, and hear lies my problem.</p> <p>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. </p> <p>Is there a better way?</p> <p>Any help would be appreciated.</p> <hr> <p><strong>Update</strong></p> <p>It seems that setting the weekday does not actually affect the date returned by the <code>dateComponents:</code> method of NSCalendar. My example code above returns the same date regardless of what is set for the weekday.</p> <p>So now I'm more stumped. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload