首页 文章

如何在iOS中将日期字符串解析为NSDate对象?

提问于
浏览
48

我试图将日期字符串从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];

}

7 回答

  • 1

    问题是最后的'Z' . 你在引号中编写它的方式,你的解析器期望你的时间字符串中有一个文字字符Z,而没有一个 . 你想要的是没有引号的Z格式字符,它表示你的时间字符串包含时区信息 . 它的作用是,字符串末尾的-05:00是时区 .

    由于您需要时区信息,因此在日期格式化程序中设置时区是毫无意义的 . 并检查Unicode格式模式的链接,该链接包含您应该信任的权威信息,而不是您在此处获得的所有答案 .

  • 0

    从iOS 10开始,提供的系统NSISO8601DateFormatter可用于此特定格式 .

  • 64

    您不需要尽可能多的单引号(仅在非日期/时间字符上需要),因此请更改:

    [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/

  • 3

    最后我和结肠有同样的问题 . 这是我用来规范日期以使 NSDate 快乐的函数 .

    /**
     * Timezones are returned to us in the format +nn:nn
     * The date formatter currently does not support IS 8601 dates, so
     * we convert timezone from the format "+07:30" to "+0730" (removing the colon) which
     * can then be parsed properly.
     */
    - (NSString *)applyTimezoneFixForDate:(NSString *)date {
        NSRange colonRange = [date rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@":"] options:NSBackwardsSearch];
        return [date stringByReplacingCharactersInRange:colonRange withString:@""];
    }
    
  • 3

    我花了一段时间才找到这个简单的答案 . 并且有很多解决方案涉及引入额外的第三方代码 .

    对于那些现在正在努力解决这个问题并仅支持iOS 6及更高版本的用户 .

    您可以将日期格式化程序设置为

    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"]
    

    这将用冒号正确处理“-05:00” .

  • 1

    解决方案是改变:

    [self.dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
    

    对于这种表示法:

    [self.dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
    

    我希望它会对你有所帮助 .

  • 1

    ISO8601DateFormatter

    我用这个库作为CocoaPod获得了很大的成功 .

    https://github.com/boredzo/iso-8601-date-formatter

    用法

    - (ISO8601DateFormatter *)dateFormatter
    {
        static ISO8601DateFormatter *dateFormatter = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            dateFormatter = [[ISO8601DateFormatter alloc] init];
            dateFormatter.includeTime = YES;
        });
    
        return dateFormatter;
    }
    
    
    NSDate *date = [[self dateFormatter] dateFromString:@"2015-05-09T13:06:00"];
    

相关问题