本文介绍了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为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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)