如何获得年份序列,因为我只获得了一个月的序列

时间:2015-08-14 13:00:48

标签: ios objective-c nsdatecomponents

我使用以下代码获得了月份序列

NSDate *aDate = [NSDate dateWithTimeInterval:row*30*24*60*60  sinceDate:self.earliestPresentedDate];

    NSDateComponents *components = [self.calendar components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:[NSDate date]];
    NSDate *today = [self.calendar dateFromComponents:components];
    components = [self.calendar components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:aDate];
    NSDate *otherDate = [self.calendar dateFromComponents:components];

    if ([today isEqualToDate:otherDate]) {

    } else {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.locale = [NSLocale currentLocale];
        formatter.dateFormat = @"MMM ";

        [lblDate setText:[formatter stringFromDate:aDate]];
    }

我想获得年度序列如何获得...请给出解决方案

2 个答案:

答案 0 :(得分:1)

制作一个功能,明确给出明年的日期,

NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
    dayComponent.year = +1;

    NSCalendar *theCalendar = [NSCalendar currentCalendar];
    NSDate *newDate = [theCalendar dateByAddingComponents:dayComponent toDate:[NSDate date] options:0];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.locale = [NSLocale currentLocale];
    formatter.dateFormat = @"yyyy";
    NSString *strDate = [formatter stringFromDate:newDate];

    NSLog(@"%@",strDate);

在标签中设置此日期。

以上我通过了当前日期,所以我将获得年份:2016年。

答案 1 :(得分:0)

简单的方法,记录这个以及随后的7年。

  NSInteger howManyYears = 8;
  NSInteger thisYear = [[NSCalendar currentCalendar] component:NSCalendarUnitYear fromDate:[NSDate date]];
  for (NSInteger i = 0; i < howManyYears; ++i) {
    NSLog(@"%ld", thisYear++);
  }

或获取字符串数组

  NSMutableArray *theYears = [NSMutableArray array];
  NSInteger howManyYears = 8;
  NSInteger thisYear = [[NSCalendar currentCalendar] component:NSCalendarUnitYear fromDate:[NSDate date]];
  for (NSInteger i = 0; i < howManyYears; ++i) {
    [theYears addObject:[NSString stringWithFormat:@"%ld", thisYear++]];
  }
  NSLog(@"%@", theYears);