Search code examples
iphoneobjective-ciosios4calendar

How to get n-th Sunday date of the month in objective c?


How to get first sunday or nth sunday or monday (any day) date in Objective C coding.

For example :- I just want to show date of friendship day in my app every year.

But, friendship comes 1st Sunday of Aug. So, date will change every year. here I need to find what is the date of 1st Sunday in Aug every year.

is there any logic to find the date of nth Sunday.


Solution

  • You need to create a NSDateComponents object and set the appropriate values, In You example you would do:

    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    
    dateComponents.year = 2011; // set the current year or whatever year you want here
    dateComponents.month = 8;
    dateComponents.weekday = 1; // sunday is 1, monday is 2, ...
    dateComponents.weekdayOrdinal = 1; // this means, the first of whatever weekday you specified
    

    To convert this into a NSDate-object, you just do:

    //you may want to use another calendar object here
    NSDate *myDate = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
    [dateComponents release]; //don't forget memory management ;)