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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4999396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:53:20  来源:igfitidea点击:

How to parse a date string into an NSDate object in iOS?

iphoneobjective-ciosnsdatensdateformatter

提问by JohnRock

I am trying to parse a date string from xml into an NSDate object in an iPhone app

我正在尝试将 xml 中的日期字符串解析为 iPhone 应用程序中的 NSDate 对象

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!

非常感谢任何帮助。谢谢!

**Based on the link reference from theChrisKent I fixed the problem like so:

**基于来自 theChrisKent 的链接参考,我修复了这个问题,如下所示:

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

}

回答by theChrisKent

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'"];

To this:

对此:

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


Documentation here: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1

此处的文档:https: //developer.apple.com/library/content/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1

Unicode Format Patterns: http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns

Unicode 格式模式:http: //unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns

Dealing with TimeZones with Colons (+00:00): http://petersteinberger.com/2010/05/nsdateformatter-and-0000-parsing/

处理带冒号的时区(+00:00):http: //petersteinberger.com/2010/05/nsdateformatter-and-0000-parsing/

回答by ucangetit

It took me a while to find the simple answer for this. and there are a lot of solutions that involve bringing in extra third party code.

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

For those who are struggling with this now and are only supporting iOS 6 and above.

对于那些现在正在为此苦苦挣扎并且仅支持 iOS 6 及更高版本的人。

You can set the date formatter to

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

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

And this will properly handle the "-05:00" with the colon.

这将正确处理带有冒号的“-05:00”。

回答by Anurag

I was having the same problems with the colon at the end. Here's a function I used to normalize the date to make NSDatehappy.

最后我的冒号也遇到了同样的问题。这是我用来规范日期以使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:@""];
}

回答by Badre

Solutions is to change :

解决方案是改变:

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

To this notation :

对于这个符号:

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

i hope it will help you.

我希望它会帮助你。

回答by Cameron Lowell Palmer

ISO8601DateFormatter

ISO8601DateFormatter

I've had great success with this library which is available as a CocoaPod.

我在这个库中取得了巨大的成功,它可以作为 CocoaPod 使用。

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

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

Usage

用法

- (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"];

回答by gnasher729

The problem is the 'Z' at the end. The way you are writing it within quotes, your parser expects a literal character Z in your time string, and there isn't one. What you want is the Z formatting character without quotes, which indicates that your time string contains time zone information. Which it does, the -05:00 at the end of your string is the time zone.

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

Since you expect time zone information, setting the time zone in your date formatter is rather pointless. And check the link to the Unicode formatting patterns, that link contains the definitive information that you should trust above all answers you get here.

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

回答by BergQuester

As of iOS 10 the system provided NSISO8601DateFormatteris available for this particular format.

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