将字符串中的日期转换为NSDate类型,在iOS中给出错误的月份和年份?

时间:2014-10-17 14:49:13

标签: ios objective-c uitableview nsdateformatter nsdatecomponents

我有一系列字典,每个字典也有一个date密钥,如doj:"2014-10-11"以及其他key:value对。所以我要做的就是对数据进行分组同一个月和同一年在一个tableViewSection中将tableView部分的标题设置为October 2014(从上面的日期开始)。但是我仍然坚持将字符串格式的日期转换为转换后的NSDate类型给了我错误的月份和年份。

  - (void)setupDataSource:(NSArray*)bookingArray
  {
     self.tableViewSections = [NSMutableArray arrayWithCapacity:0];
     self.tableViewCells = [NSMutableDictionary dictionaryWithCapacity:0];

     NSCalendar* calendar = [NSCalendar currentCalendar];
     NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
     NSDateFormatter* dateFormatter_table = [[NSDateFormatter alloc] init];
     dateFormatter.locale = [NSLocale currentLocale];
     dateFormatter.timeZone = calendar.timeZone;

    [dateFormatter setDateFormat:@"yyyy-MM-dd"];

    [dateFormatter_table setDateFormat:@"MMMM YYYY"];

    NSUInteger dateComponents = NSYearCalendarUnit | NSMonthCalendarUnit;
    NSInteger previousYear = -1;
    NSInteger previousMonth = -1;
    NSMutableArray* tableViewCellsForSection = nil;

    for (NSDictionary *dictObject in bookingList) {
        NSString *dateString = [dictObject objectForKey:@"doj"];   //gives "2014-10-11"
        NSDate *date = [dateFormatter dateFromString:dateString];
        NSString *tempDate = [dateFormatter_table stringFromDate:date];

        NSLog(@"Table Header Date : %@", tempDate);         //gives October 2014 properly
        NSDateFormatter *newformatter = [[NSDateFormatter alloc]init];
        [newformatter setDateFormat:@"MMMM YYYY"];
        NSDate *dateForTable = [newformatter dateFromString:tempDate];

        NSLog(@"Table Header Date : %@", dateForTable);    //gives December 2013

        NSDateComponents* components = [calendar components:dateComponents fromDate:dateForTable];


       NSInteger year = [components year];
       NSInteger month = [components month];

       if (year != previousYear || month != previousMonth)
       {
          NSString* sectionHeading = [newformatter stringFromDate:dateForTable];
          [self.tableViewSections addObject:sectionHeading];
          tableViewCellsForSection = [NSMutableArray arrayWithCapacity:0];
          [self.tableViewCells setObject:tableViewCellsForSection forKey:sectionHeading];
          previousYear = year;
          previousMonth = month;

      }
      [tableViewCellsForSection addObject:dateForTable];

    }


 }

0 个答案:

没有答案