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 回答