Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

harryslotwiner

macrumors newbie
Original poster
Mar 28, 2012
19
0
I have an app in which I am downloading RSS feeds from websites and I need to sort the articles by date. Is there any way convert a string to a date but not know the format of the string?
 
There would be manual ways to convert lots of formats to a known format it if you know every possible format the string could be.
 
That would be my last resort as that would leave it very possible that I don't acknowledge a date format and I can't organize any of the articles from that website.

----------

I realized that is a specified date format for RSS (RFC 822), so now I just have to hope people follow that. However there are option parts of it. This is a helpful URL for anyone else with the problem: [Link].
 
Thanks, that worked perfectly and makes me feel a lot more secure about correctly detecting the dates. So for anyone who needs to know how to detect a date with an unknown format, here's how:
Code:
+ (NSString *)convertToDate:(NSString *)string {
    
    NSError *error = nil;
    NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeDate error:&error];
    NSArray *matches = [detector matchesInString:string options:0 range:NSMakeRange(0, [string length])];
    
    NSDate *date;
    for (NSTextCheckingResult *match in matches) {
        date = match.date;
        NSLog(@"Got date: %@", match.date);
    }
    
    if (date) {
        NSString *stringFromDate = [NSString stringWithFormat:@"%f", [date timeIntervalSince1970]];
        return stringFromDate;
    } else {
        NSLog(@"Error: %@", error);
    }
}

In this I am converting it to seconds since the Unix Epoch for the simplicity of sorting.
 
Why not keep the NSDate object if you add it as a property on your object? which I assume you are doing with the string, then using that as the key path for sorting. The NSDate would still sort your data effectively and you could then use it if you want the date again for the User interface or otherwise.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.