如何在iOS中将日期字符串解析为NSDate对象? [英] How to parse a date string into an NSDate object in iOS?
问题描述
我正在尝试将日期字符串从xml解析为iPhone应用程序中的NSDate对象
I am trying to parse a date string from xml into an NSDate object in an iPhone app
我知道之前一定要问过这个问题,不过我相信我有正确的语法,但它不起作用。我的代码有问题吗?
I am aware this must have been asked before, however, I believe I have the right syntax, but it is not working. Is there a problem with my code?
我需要解析的日期字符串是:
The date string I need to parse is:
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 ];
}
任何帮助都非常感谢。谢谢!
Any help greatly appreciated. Thanks!
**基于来自theChrisKent的链接引用我修复了这样的问题:
**Based on the link reference from theChrisKent I fixed the problem like so:
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];
}
推荐答案
你不要我们需要尽可能多的单引号(仅限非日期/时间字符),所以请更改:
You don't need near as many single quotes as you have (only needed on non date/time characters), so change this:
[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.currentParsedCharacterData stringByReplacingOccurrencesOfString:@":" withString:@"" options:0 range:NSMakeRange([self.currentParsedCharacterData length] – 5,5)]];
Unicode格式模式: http://unicode.org/reports/tr35 /tr35-6.html#Date_Format_Patterns
Unicode Format Patterns: http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
处理带冒号的时区(+00:00): http://petersteinberger.com/2010/05/nsdateformatter-and-0000-parsing/
Dealing with TimeZones with Colons (+00:00): http://petersteinberger.com/2010/05/nsdateformatter-and-0000-parsing/
这篇关于如何在iOS中将日期字符串解析为NSDate对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!