I am working in a project where I need to show current and previous 6 months with year. I am using below code to do this.
for (int i=0; i< numberofMonths; i++) {
NSString *index=[NSString stringWithFormat:@"%d",i+1];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [NSDateComponents new];
comps.month = - (i+1);
NSDate *date = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
NSDateComponents *components = [calendar components:NSMonthCalendarUnit|NSYearCalendarUnit fromDate:date]; // Get necessary date
currentYear = [components year];
currentmonth=[components month];
yearstring = [[NSString alloc]initWithFormat:@"%ld",currentYear];
yearstring=[yearstring substringFromIndex:MAX((int)[yearstring length]-2, 0)];
monthName = [[df monthSymbols] objectAtIndex:(currentmonth-1 )];
NSString *string=[NSString stringWithFormat:@"%@, %@",monthName,yearstring];
}
This code works fine for all months. But when I set the current month as January/February. Then it does gives error of array range. Please advice
Your problem is that when you call [[df monthSymbols] objectAtIndex:(currentmonth-1 )];
for currentMonth of 1 then you end up with an invalid month number. Much simpler code to achieve what you are after is -
int numberOfMonths=6;
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:@"MMMM, YY" ];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *now=[NSDate date];
NSDateComponents *comps = [NSDateComponents new];
for (int i=-numberOfMonths; i< 1; i++) {
comps.month = i;
NSDate *newDate = [calendar dateByAddingComponents:comps toDate:now options:0];
NSString *string=[formatter stringFromDate:newDate];
NSLog(@"date=%@",string);
}