如何在 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
我用来解析它的代码是:
The code I am using to parse it is:
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屋!