Question

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy";
NSDate *date = [dateFormatter dateFromString:@"2011"];
for(int month=0;month<=12;month++)
   {
dateFormatter.dateFormat=@"MMMM";
NSString * monthString = [[dateFormatter stringFromDate:date] capitalizedString];
NSLog(@"month: %@", monthString);
    }

I need to display all the month in a particular year.Example if i give the year as 2011 i want the entire 12 month in that year i used tis above code.

But the answer,i am getting one month as january that printed in 12 times ,but i need to get whole 12 months in the particular year.

Was it helpful?

Solution

Try this following code.

      //NSInteger startingMonth = 1;
    NSInteger startingYear = 2014;

    // we'll need this in several places
    NSCalendar *cal = [NSCalendar currentCalendar];

    // build the first date (in the starting month and year)
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    //[comps setMonth:startingMonth];
    [comps setYear:startingYear];
    // [comps setDay:1];
    NSDate *date = [cal dateFromComponents:comps];

    // this is our output format
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMMM YYYY"];
    NSDateFormatter *format1 = [[NSDateFormatter alloc] init];
    [format1 setDateFormat:@"MM yy"];
    // we need NSDateComponents for the difference, i.e. at each step we
    // want to go one month further
    NSDateComponents *comps2 = [[NSDateComponents alloc] init];
    [comps2 setMonth:1];

    for (int i= 0; i < 12; i++) {
        NSLog(@"month list %@", [format1 stringFromDate:date]);
        NSString *str=[NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
        [mothlist_ary addObject:str];
        NSLog(@"GET MONTH %@",mothlist_ary);
        // add 1 month to date
        date = [cal dateByAddingComponents:comps2 toDate:date options:0];

    }

OTHER TIPS

Try This...

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy";
    NSDate *date = [dateFormatter dateFromString:@"2011"];

    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:( NSMonthCalendarUnit) fromDate:date];


    dateFormatter.dateFormat=@"MMMM";

    for(int month=1;month<=12;month++)
    {
        [components setMonth:(month)];
        NSDate *lastMonth = [cal dateFromComponents:components];

        NSString * monthString = [[dateFormatter stringFromDate:lastMonth] capitalizedString];
        NSLog(@"month: %@", monthString);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top