按 NSDate 排序 table 个部分

Sorting table sections by NSDate

如何对 NSDate 进行排序,以便如果某个日期的时间是 05:00 星期天早上,它会停留在星期六 "night",但在列表的最后?

我根据 JSON 数据

按日期对我的表格视图部分进行排序
[[API sharedInstance] commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"fodboldStream", @"command", nil] onCompletion:^(NSDictionary *json) {

    //got stream
    //NSLog(@"%@",json);
    [[API sharedInstance] setSoccer: [json objectForKey:@"result" ]];

    games = [json objectForKey:@"result"];


    sections = [NSMutableDictionary dictionary];

    for (NSDictionary *game in games) {
        NSNumber *gameType = game[@"dato"];
        NSMutableArray *gamesForType = sections[gameType];
        if (!gamesForType) {
            gamesForType = [NSMutableArray array];
            sections[gameType] = gamesForType;
        }
        [gamesForType addObject:game];


    }
   // NSLog(@"%@",sections);

    [fodboldTabel reloadData];
}];

这是我的部分 header:

- (NSString*) tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section {

    //...if the scetions count is les the 1 set title to opdating ...

    if ([[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section]] count] < 1) {
        return @"Opdater....";

    } else {

        // ..........seting tabelheader titel to day and date..................
        NSString *str = [[[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section];

        NSDate *date = [NSDate date];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init] ; // here we create NSDateFormatter object for change the Format of date..
        [dateFormatter setDateFormat:@"yyyy-MM-dd"]; //// here set format of date which is in your output date (means above str with format)
        date = [dateFormatter dateFromString:str];

        dateFormatter.locale=[[NSLocale alloc] initWithLocaleIdentifier:@"da_DK"];

        dateFormatter.dateFormat=@"MMMM";
        NSString * monthString = [[dateFormatter stringFromDate:date] capitalizedString];

        dateFormatter.dateFormat=@"EEEE";
        NSString * dayString = [[dateFormatter stringFromDate:date] capitalizedString];

        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSInteger units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday;
        NSDateComponents *components = [calendar components:units fromDate:date];

        NSInteger year = [components year];
        //  NSInteger month=[components month];       // if necessary
        NSInteger day = [components day];
        //NSInteger weekday = [components weekday]; // if necessary


        NSString *sectionLbl = [NSString stringWithFormat: @"%@ %li %@ %li", dayString, (long)day, monthString, (long)year];
        return sectionLbl;
    }
}

这是一张图片,你可以看到 header 说 søndag(星期日)并且比赛开始 01:35 上午所以比赛在星期天早上在电视上播放,但我希望在星期六.部分..... 所以实际上我只是让 "day" 从早上 5 点到凌晨 5 点而不是 00:00 - 00:00

您应该确定 timeZoneNSDateFormatter 一起使用,以便在构建 headers 部分时使用。

例如,下面我展示了一系列事件,按 when 属性 排序,除了 headers 部分将在某个预定的时区,而不是我的设备的特定时区。因此,我首先使用适当的 NSTimeZone:

// Given some array of sorted events ...

NSArray *sortedEvents = [events sortedArrayUsingDescriptors:@[[[NSSortDescriptor alloc] initWithKey:@"when" ascending:YES]]];

// Let's specify a date formatter (with timezone) for the section headers.

NSDateFormatter *titleDateFormatter = [[NSDateFormatter alloc] init];
titleDateFormatter.dateStyle = NSDateFormatterLongStyle;
titleDateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];   // use whatever you want here; I'm just going to figure out sections in GMT even though I'm currently in GMT-5

// Now let's build our array of sections (and the list of events in each section)
// using the above timezone to dictate the sections.

self.sections = [NSMutableArray array];

NSString *oldTitle;
for (Event *event in sortedEvents) {
    NSString *title = [titleDateFormatter stringFromDate:event.when]; // what should the section title be

    if (![oldTitle isEqualToString:title]) {                          // if different than last one, add new section
        [self.sections addObject:[Section sectionWithName:title]];
        oldTitle = title;
    }

    [[(Section *)self.sections.lastObject items] addObject:event];    // add event to section
}

但是,当我显示单元格内容时,如果我不触摸 timeZone 参数,它将默认显示当前时区的实际时间。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"EventCell";
    EventCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    Section *section = self.sections[indexPath.section];
    Event *event = section.items[indexPath.row];

    // This formatter really should be class property/method, rather than instantiating 
    // it each time, but I wanted to keep this simple. But the key is that
    // I don't specify `timeZone`, so it defaults to current timezone.

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
    formatter.timeStyle = NSDateFormatterMediumStyle;

    cell.eventTimeLabel.text = [formatter stringFromDate:event.when];

    // do additional cell population as you see fit

    return cell;
}

对于 header 部分,使用我在构建支持此 table 视图的模型的例程中提出的部分名称(即,使用 hard-coded 时区)。

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [(Section *)self.sections[section] sectionName];
}

如您所见,时间按当前时区列出,但它们按我在构建部分列表的代码中指定的预定 NSTimeZone 分组。

显然,我只是使用格林威治标准时间作为我的时区,但您可能想使用事件地点的时区或 NBA 篮球,一些任意的美国时区。但希望这能说明基本思想。创建部分时使用一个时区,显示实际时间时使用默认时区。