gpt4 book ai didi

ios - 如何在 iOS 中显示当前和前 6 个月的年份?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:15:59 24 4
gpt4 key购买 nike

我在一个项目中工作,我需要显示当前和过去 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 的 currentMonth 调用 [[df monthSymbols] objectAtIndex:(currentmonth-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);
}

关于ios - 如何在 iOS 中显示当前和前 6 个月的年份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24243048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com