Hey Tom,

as it happens, I just did this a few weeks ago for my current project. The 
following is straight out of my code, and computes the next Wed or Sat from a 
given date.

Enjoy!
WT

- (NSDate*) nextWedOrSatFromDate: (NSDate*) date;
{
    NSCalendar* cal = [[NSCalendar alloc]
        initWithCalendarIdentifier: NSGregorianCalendar];

    NSDateComponents* comps = [cal components: NSWeekdayCalendarUnit
                                     fromDate: date];

    // [comps weekday] gives Sun = 1, Mon = 2, etc, Sat = 7,
    // so take mod 7 to make Sat = 0.
    
    NSInteger weekday = [comps weekday] % 7;

    // Sat = 0, Sun = 1, Mon = 2, Tue = 3,
    // Wed = 4, Thu = 5, Fri = 6

    if (weekday < 4) // it's Sat or beyond, but before Wed
    {
        // add enough full days to get to Wed

        NSInteger secs = (4 - weekday) * 24 * 60 * 60;
        date = [date dateByAddingTimeInterval: secs];
    }
    else // it's beyond Tue but before Sat
    {
        // add enough full days to get to Sat

        NSInteger secs = (7 - weekday) * 24 * 60 * 60;
        date = [date dateByAddingTimeInterval: secs];
    }

    [cal release];
    
    return date;
}

On Dec 31, 2010, at 2:03 AM, Tom Jones wrote:

> Hello,
> I'm trying to calculate next occurrence of a NSDate object. Based on a "Start 
> Date" ( e.g. 2010-12-10, Friday ) I would like to know the date of the next 
> Friday occurrence from today ( e.g. 2010-12-30, Thursday ).  
> 
> Example:
> StartDate = 2010-12-10
> CurrentDate = 2010-12-30
> Next Occurrence = 2010-12-31 <-Answer
> 
> I have not done this before so I'm not sure how to tackle this.
> 
> Thanks,
> tom
> 
> 
> _______________________________________________
> 
> Cocoa-dev mailing list ([email protected])
> 
> Please do not post admin requests or moderator comments to the list.
> Contact the moderators at cocoa-dev-admins(at)lists.apple.com
> 
> Help/Unsubscribe/Update your Subscription:
> http://lists.apple.com/mailman/options/cocoa-dev/jrcapab%40gmail.com
> 
> This email sent to [email protected]

_______________________________________________

Cocoa-dev mailing list ([email protected])

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [email protected]

Reply via email to