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);
}
我需要显示特定年份的所有月份.例如,如果我将年份作为2011年,我想要在那一年的整个12个月,我使用上面的代码.
但答案是,我将在12月印刷一个月,但是我需要在特定年份整整12个月.
最佳答案 请尝试以下代码.
//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];
}