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

发布于 2024-10-17 22:57:37 字数 1334 浏览 2 评论 0原文

我正在尝试将 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];

}

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!

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

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

梦回梦里 2024-10-24 22:57:37

您不需要像您拥有的那样多的单引号(仅在非日期/时间字符上需要),因此更改此:

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

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

Unicode Format Patterns: 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/

冬天旳寂寞 2024-10-24 22:57:37

最后我的结肠也遇到了同样的问题。这是我用来标准化日期以使 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:@""];
}

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

/**
 * 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:@""];
}
痴梦一场 2024-10-24 22:57:37

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

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

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

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

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

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.

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.

寒冷纷飞旳雪 2024-10-24 22:57:37

解决方案是更改:

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

对此表示法:

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

我希望它会对您有所帮助。

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.

眼泪都笑了 2024-10-24 22:57:37

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

ISO8601DateFormatter

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

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"];
云胡 2024-10-24 22:57:37

问题是最后的“Z”。您在引号内编写它的方式,您的解析器期望时间字符串中有一个文字字符 Z,但实际上没有。您想要的是不带引号的 Z 格式字符,这表明您的时间字符串包含时区信息。确实如此,字符串末尾的 -05:00 是时区。

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

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.

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.

情栀口红 2024-10-24 22:57:37

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文