0

在我的应用程序中,我将日期解析为来自 RSS 提要的字符串,并尝试按日期对它们进行排序。当我对字符串执行标准 sortDescriptor 时,它的排序很好,但是因为格式是“DD/MM/YYYY HH:MM:SS”,所以它是按天而不是整个日期排序的,所以我的列表不在按时间顺序。

因此,我试图将从 RSS 解析的日期字符串转换为 NSDate,然后按日期排序。但是,当我这样做时,它返回 null。谁能指定我哪里出错了?

        // Loop through XML data
    [rxml iterate:@"channel" usingBlock:^(RXMLElement *supportElement) {
        [supportElement iterate:@"item" usingBlock:^(RXMLElement *repElement) {

            // Assign element to string
            NSString *title = [repElement child:@"title"].text;
            NSString *description = [repElement child:@"description"].text;
            NSString *imageurl = [repElement child:@"image"].text;
            NSString *mystartDate = [repElement child:@"start_date"].text;
            NSString *myendDate = [repElement child:@"end_date"].text;


            // DESCRIPTION FORMATTING
            description = [customStringParser parseHTML:description];
            description = [customStringParser parseLinesMultiple:description];
            description = [customStringParser removeSocialSignifiers:description];
            currentFeed.description = description;

            // DATE FORMATTING

            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"DD/MM/YYYY HH:MM:SS"];
            [dateFormatter setFormatterBehavior:NSDateFormatterBehaviorDefault];
            NSDate *startDate = [dateFormatter dateFromString:mystartDate];
            NSDate *endDate = [dateFormatter dateFromString:myendDate];

            currentFeed.startDate = startDate;
            currentFeed.endDate = endDate;


            NSLog(@"%@", startDate);
            NSLog(@"%@", endDate);


            // Add a new object to the feeds array
            [eventsFeeds addObject:currentFeed];
        }];
        [loadingView removeFromSuperview];
        [self.loadingIndicator stopAnimating];


        //sort array
        NSSortDescriptor *sortByDate = [NSSortDescriptor sortDescriptorWithKey:@"startDate" ascending:NO];
        [eventsFeeds sortUsingDescriptors:[NSArray arrayWithObject:sortByDate]];

然后我还相信我可能必须将 NSDate 转换回字符串,以便可以在视图控制器上的 detailTextLabel 中打印它,这是正确的吗?谢谢。

4

2 回答 2

1
NSArray *arr = [folderContent sortedArrayUsingFunction:dateSort context:nil];



//The date sort function



NSComparisonResult dateSort(NSString *s1, NSString *s2, void *context) {


NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"];

NSDate *d1 = [formatter dateFromString:[s1 substringFromIndex:[s1 length]-19]];
NSDate *d2 = [formatter dateFromString:[s2 substringFromIndex:[s2 length]-19]]; 

//  return [d1 compare:d2]; // ascending order
return [d2 compare:d1]; // descending order
 }
于 2014-08-13T09:29:53.327 回答
0

你应该改变:

[dateFormatter setDateFormat:@"DD/MM/YYYY HH:MM:SS"];

[dateFormatter setDateFormat:@"dd MMM yyyy"];
于 2013-11-11T10:02:44.177 回答