Domanda

I want to parse a date string that I receive from a web service. However, I sometimes receive the date with decimal component and sometimes without decimal component. Also, sometimes the date comes with a different number of decimal digits.

Assume you got the following date:

NSString *dateString = @"2013-07-22T220713.9911317-0400";

How can remove the decimal values? I want to end up with:

 @"2013-07-22T220713-0400";

So I can process it with the DateFormatter that uses no decimal.

È stato utile?

Soluzione 2

Based on @JeffCompton 's suggestion I ended up doing this:

+ (NSDate *)dateFromISO8601:(NSString *)dateString {
    if (!dateString) return nil;
    if ([dateString hasSuffix:@"Z"]) {
        dateString = [[dateString substringToIndex:(dateString.length - 1)] stringByAppendingString:@"-0000"];
    }

    NSString *cleanDateString = dateString;

    NSArray *dateComponents = [dateString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"."]];
    if ([dateComponents count] > 1){
        NSArray *timezoneComponents = [[dateComponents objectAtIndex:1] componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"-"]];

        if ([timezoneComponents count] > 1){
            cleanDateString = [NSString stringWithFormat:@"%@-%@", [dateComponents objectAtIndex:0], [timezoneComponents objectAtIndex:1]];
        }
    }

    dateString = [cleanDateString stringByReplacingOccurrencesOfString:@":" withString:@""];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-d'T'HHmmssZZZ";

    NSDate *resultDate = [dateFormatter dateFromString:dateString];

    return resultDate;
}

This is a modification of some open-source code but I lost the reference to the original code.

The reason for all the modifications is that I am connecting to API's that can give me the date with decimals or without, and sometimes without the : separating HH, mm, and ss.

Altri suggerimenti

You could use a regular expression to match the first occurrence of a decimal followed by numbers, and remove them:

NSString *dateString = @"2013-07-22T220713.9911317-0400";

NSRegularExpression * regExp = [NSRegularExpression regularExpressionWithPattern:@"\\.[0-9]*" options:kNilOptions error:nil];

dateString = [dateString stringByReplacingCharactersInRange:[regExp rangeOfFirstMatchInString:dateString options:kNilOptions range:(NSRange){0, dateString.length}] withString:@""];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top