NSDateFormatter在OS 4.0中返回nil [英] NSDateFormatter returning nil in OS 4.0
本文介绍了NSDateFormatter在OS 4.0中返回nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在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为零。
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文