Search code examples
objective-cnscalendar

NSCalendar class to find the Date of a Weekday


I m creating an calendar based application for that i have used the NSCalendar class

now i want to get the Date of a perticular weekday means if todays date is 8th dec 2012 and i pass the weekday 2 then it has to be written me the date of monday i.e. 10th Dec 2012

How to achieve this


Solution

  • Use NSDateComponents and NSCalendar.

    NSDate *date = [NSDate date]; // 2012-12-08 09:46:31 +0000
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setDay:2]; // your example of 2 days
    date = [calendar dateByAddingComponents:components
                                     toDate:date options:0];
    // 2012-12-10 09:46:31 +0000