Joh*_*ock 48 iphone objective-c nsdate nsdateformatter ios
我试图将日期字符串从xml解析为iPhone应用程序中的NSDate对象
我知道之前一定要问过,但是,我相信我有正确的语法,但它不起作用.我的代码有问题吗?
我需要解析的日期字符串是:
2011-01-21T12:26:47-05:00
Run Code Online (Sandbox Code Playgroud)
我用来解析它的代码是:
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 ];
}
Run Code Online (Sandbox Code Playgroud)
任何帮助非常感谢.谢谢!
**基于来自ChrisKent的链接参考,我修复了这样的问题:
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];
}
Run Code Online (Sandbox Code Playgroud)
the*_*ent 64
您不需要尽可能多的单引号(仅在非日期/时间字符上需要),因此请更改:
[self.dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
Run Code Online (Sandbox Code Playgroud)
对此:
[self.dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
...
self.currentQuestion.updated = [self.dateFormatter dateFromString:[self.currentParsedCharacterData stringByReplacingOccurrencesOfString:@":" withString:@"" options:0 range:NSMakeRange([self.currentParsedCharacterData length] – 5,5)]];
Run Code Online (Sandbox Code Playgroud)
文档:https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1
Unicode格式模式:http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
使用冒号处理时区(+00:00):http://petersteinberger.com/2010/05/nsdateformatter-and-0000-parsing/
| 归档时间: |
|
| 查看次数: |
42370 次 |
| 最近记录: |