Date from String With an Inconsistent Format

Discussion in 'iOS Programming' started by harryslotwiner, Jul 23, 2012.

  1. harryslotwiner macrumors newbie

    Joined:
    Mar 28, 2012
    #1
    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?
     
  2. xArtx macrumors 6502a

    Joined:
    Mar 30, 2012
    #2
    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.
     
  3. harryslotwiner thread starter macrumors newbie

    Joined:
    Mar 28, 2012
    #3
    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].
     
  4. MattInOz macrumors 68030

    MattInOz

    Joined:
    Jan 19, 2006
    Location:
    Sydney
  5. harryslotwiner thread starter macrumors newbie

    Joined:
    Mar 28, 2012
    #5
    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.
     
  6. MattInOz macrumors 68030

    MattInOz

    Joined:
    Jan 19, 2006
    Location:
    Sydney
    #6
    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.
     
  7. harryslotwiner thread starter macrumors newbie

    Joined:
    Mar 28, 2012
    #7
    Thanks, again. I don't know why I didn't think about it that way, but I'm doing that now.
     

Share This Page