0

NSDateFormatterを使用して、着信文字列からNSDateを取得します。私はこのコードを持っています:

stringToUpdate = [stringToUpdate stringByReplacingOccurrencesOfString:@"T" withString:@" "];

NSMutableString* dateWithoutColonString = [stringToUpdate mutableCopy];

NSRegularExpression* lastColonRegex = [NSRegularExpression
                                       regularExpressionWithPattern:@"([\\+\\-][0-9][0-9]):"
                                       options:NSRegularExpressionCaseInsensitive
                                       error:nil];

[lastColonRegex replaceMatchesInString:dateWithoutColonString
                               options:NSRegularExpressionCaseInsensitive
                                 range:NSMakeRange(0, [stringToUpdate length])
                          withTemplate:@"$1"];

NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
[dateformatter setDateFormat:@"yyyy-MM-dd hh:mm:ssZZZ"];

NSDate *myDate = [dateformatter dateFromString: dateWithoutColonString];

これは、着信文字列ごとに異なる動作をします。意味:

NSString *stringToUpdate = @"2013-02-05T17:20:58+01:00";

常に失敗しますが

NSString *stringToUpdate = @"2013-02-07T12:26:41+01:00";

常に成功します。着信文字列の長さは両方で同じであるため、機能的な文字は使用しないでください。何が起こっているのかヒントをいただければ幸いです。

4

1 に答える 1

0

DateFromStringは単にバグがあるようです。使用する:

if (![[self dateformatter] getObjectValue:&myDate forString:stringToUpdate range:nil error:&error]) {
    NSLog(@"Date '%@' could not be parsed: %@", stringToUpdate, error);
} else {
    //NSLog(@"%@", myDate);
}

NSString *text;

NSTimeInterval timeInSeconds = [myDate timeIntervalSinceNow];
timeInSeconds = timeInSeconds * -1;

正の秒数を取得します。

于 2013-02-12T07:29:12.930 に答える