Display month list for this particular year in Xcode 5

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 the whole month in a particular year. For example, if I give a year like 2011, I want the whole 12-month year this year, I used this code above.

But the answer is, I get one month, like January, which is printed 12 times, but I need to get as much as 12 months in a particular year.

+4
source share
2 answers

Try the 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];

    }
+1
source

Try it...

    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);
    }
+1
source

Source: https://habr.com/ru/post/1526297/


All Articles