我正在一个项目中工作,我需要显示当前和之前6个月的年份。我使用下面的代码来执行此操作。
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];
}
此代码适用于所有月份。但是当我把当前月份定为1月/ 2月时。然后它确实给出了数组范围的错误。 请建议
答案 0 :(得分:4)
您的问题是,当您将[[df monthSymbols] objectAtIndex:(currentmonth-1 )];
的当前月份调用为1时,您的月份号码将无效。更简单的代码来实现你的目标是 -
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);
}
答案 1 :(得分:2)
您可以使用NSDateFormatter
从NSDate
获取年份和月份字符串。不需要做所有这些马戏团。检查我的代码,这是你想要的吗?
for (int i=0; i< 6; i++) {
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
NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:@"MMMM, yy"];
NSString *dateString = [df stringFromDate:date];
NSLog(@"%@ ",dateString);
}