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

问题描述 投票:2回答:2

我正在一个项目中,我需要显示当前和之前的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];
    }

此代码在所有月份都可以正常工作。但是当我将当前月份设置为一月/二月时。然后它确实给出了数组范围的误差。请指教

ios iphone nsdate nsdateformatter nscalendar
2个回答
4
投票

您的问题是,当您为currentMonth调用1的[[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);
}

2
投票

您可以使用NSDateFormatterNSDate获取年和月字符串。不需要做所有这些杂技。检查我的代码,这是您想要的吗?

  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);
}
© www.soinside.com 2019 - 2024. All rights reserved.