Sorting table sections by NSDate

女生的网名这么多〃 提交于 2019-12-12 01:54:01

问题


How do I sort NSDate so that if a time on a date is 05:00 Sunday morning, it stays on Saturday "night", but last on the list?

I sort my tableview sections by date from JSON data

[[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];
}];

and here is my section 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;
    }
}

Here is a image, as you can see the header says søndag(Sunday) and the game start 01:35 am so the game is shown on tv sunday morning but i want that in Saturday. section..... so actually i just wat the "day" to go from 5am to 5am instead of 00:00 - 00:00


回答1:


You should identify a timeZone to use in conjunction with a NSDateFormatter to be used when constructing the section headers.

For example, below I show a series of events, sorted by the when property, except that the section headers will be in some predetermined timezone, not my device's particular timezone. So, I first build my model backing my table (an array of Section objects, each which has an array of items) using a date formatter of the appropriate 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
}

But, when I'm displaying the cell contents, if I don't touch the timeZone parameter, it will default to showing the actual time in the current 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;
}

For section header, use that section name I came up with in the routine that built the model backing this table view (i.e., using that hard-coded timezone).

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

As you can see, the times are listed in current time zone, but they are grouped by the predetermined NSTimeZone I specified in the code that built the list of sections.

Clearly, I just used GMT for my timezone, but you might want to use the timezone for the venue of the event or for NBA basketball, some arbitrary US timezone. But hopefully this illustrates the basic idea. Use one timezone when creating the sections, and the default timezone when showing the actual time.



来源:https://stackoverflow.com/questions/28793654/sorting-table-sections-by-nsdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!