NSDateFormatter奇怪的dateFromString行为

时间:2013-02-07 14:10:45

标签: nsdate nsdateformatter

我使用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";

总是成功。传入字符串的长度对于两者都是相同的,因此不应该有任何功能字符。任何暗示正在发生的事情将不胜感激!

1 个答案:

答案 0 :(得分: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;

获得正数秒。