|
问:在一个iPhone应用程序中,我尝试从xml中解析一个日期字符串成为一个NSDate对象。
我记得这个问题以前已经被问过了,然而,我相信我有一个正确的代码,但是它没有运行。我使用的代码有什么问题吗?
我需要解析的日期字符串是:
- 2011-01-21T12:26:47-05:00
复制代码
我使用了以下的代码解析它:
- self.dateFormatter = [[NSDateFormatter alloc] init];
- [self.dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
- [self.dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];
- [self.dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
- ...
- else if([elementName isEqualToString:kUpdated]){
- self.currentQuestion.updated = [self.dateFormatter dateFromString:self.currentParsedCharacterData ];
- }
复制代码
对于任何的帮助非常有好的。谢谢!
基于某一个人的参考链接,我确定有如下的问题:
- else if([elementName isEqualToString:kLastOnDeck]){
- NSString *dateStr = self.currentParsedCharacterData;
- // we need to strip out the single colon
- dateStr = [dateStr stringByReplacingOccurrencesOfString:@":"
- withString:@""
- options:0
- range:NSMakeRange([dateStr length] - 5,5)];
- self.currentQuestion.lastOnDeck = [dateFormatter dateFromString:dateStr];
- }
复制代码
答:你不需要在设置格式这条语句中使用很多单引号(仅需要在非date/time字符串上),所以改变以下代码:
- [self.dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
复制代码
将其改为如下代码:
- [self.dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
- ...
- self.currentQuestion.updated = [self.dateFormatter dateFromString:[self.currentParsedChacurrentParsedCharacterData stringByReplacingOccurrencesOfString:@":" withString:@"" optioptions:0 range:NSMakeRange([self.currentParsedCharacterData length] – 5,5)]];
复制代码
文档的链接:
http://developer.apple.com/libra ... /uid/TP40002369-SW1
Unicode格式模式的链接
tp://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
处理TimeZone使用冒号(+00:00)
http://petersteinberger.com/2010 ... r-and-0000-parsing/
|
|