0

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.

4

2 回答 2

0

根据@JeffCompton 的建议,我最终这样做了:

+ (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;
}

这是对一些开源代码的修改,但我丢失了对原始代码的引用。

所有修改的原因是我连接到 API,它可以给我带小数或不带小数的日期,有时没有:分隔 HH、mm 和 ss。

于 2013-07-29T03:04:22.873 回答
0

您可以使用正则表达式匹配第一次出现的小数,然后是数字,然后删除它们:

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:@""];
于 2013-07-29T02:16:39.640 回答