我正在try 将xml中的日期字符串解析为iPhone应用程序中的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 ];
}

非常感谢您的帮助.谢谢

**基于来自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];

}

推荐答案

你不需要像现在这样多的单引号(只需要在非日期/时间字符上),所以改变一下:

[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)]];

这里的文档: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/

Objective-c相关问答推荐

Objective c 判断文本字段是否为空

NSDateFormatter,我做错了什么还是这是一个错误?

Objective-c中release和dealloc的区别

如何删除警告按钮的框架在运行时会有所不同.

将类作为参数传递?

iOS 块和对自身的强/弱引用

UISearchbar 键盘搜索按钮操作

在 Xcode 中为无法识别的 Select 器创建断点

如何在 XCode 4 中创建 dSYM 文件?

如何获取 iPhone 的当前方向?

setStatusBarHidden 在 iOS 9.0 中已弃用

Objective-C 的 Eclipse 插件?

Interface Builder 中的 IBOutletCollection 集排序

如何为图层 shadowOpacity 设置动画?

如何在 iPhone 中将 NSData 转换为字节数组?

字符串的静态 NSArray - 如何/在哪里初始化视图控制器

IOHIDFamily 的神秘控制台错误

UILabel 根据要显示的文本自动调整大小

Objective-c 2.0 中的可选参数?

如何更改标签栏上的非活动图标/文本 colored颜色 ?