我在 OS 3.x 上运行了以下代码
I had the following code working on on OS 3.x
NSString *stringDate = @"2010-06-21T20:06:36+00:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *theDate = [dateFormatter dateFromString:stringDate];
NSLog(@"%@",[dateFormatter stringFromDate:theDate]);
但现在在iOS4模拟器下最新的xcode 3.2.3中,变量theDate为nil.
but now in the newest xcode 3.2.3 under the iOS4 simulator, the varialble theDate is nil.
我查看了类参考,并没有看到使用这些特定方法为 iOS4 弃用或实现的任何内容.我遗漏了什么?
I have looked through the class reference and do not see anything deprecated or implemented differently for iOS4 with these specific methods. What did i leave out?
我发现如果你这样做,它会有效(见下文).关键是使用方法:- [NSDateFormatter getObjectValue:forString:range:error:]
I found out it works if you do it this way (see below). The key is using the method:
- [NSDateFormatter getObjectValue:forString:range:error:]
而不是
-[NSDateFormatter dateFromString]
完整代码:
+ (NSDate *)parseRFC3339Date:(NSString *)dateString
{
NSDateFormatter *rfc3339TimestampFormatterWithTimeZone = [[NSDateFormatter alloc] init];
[rfc3339TimestampFormatterWithTimeZone setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];
[rfc3339TimestampFormatterWithTimeZone setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *theDate = nil;
NSError *error = nil;
if (![rfc3339TimestampFormatterWithTimeZone getObjectValue:&theDate forString:dateString range:nil error:&error]) {
NSLog(@"Date '%@' could not be parsed: %@", dateString, error);
}
[rfc3339TimestampFormatterWithTimeZone release];
return theDate;
}
这篇关于NSDateFormatter 在 OS 4.0 中返回 nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!