使用NSDateFormatter解析RFC 822日期 [英] Parsing a RFC 822 date with NSDateFormatter

查看:286
本文介绍了使用NSDateFormatter解析RFC 822日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NSDateFormatter来解析iPhone上的RFC 822日期。但是,没有办法在日期格式中指定可选元素。在RFC 822规范中有几个可选部分是破坏日期解析器。如果没有任何效果,我可能必须编写一个自定义解析器来遵守规范。

I'm using a NSDateFormatter to parse a RFC 822 date on the iPhone. However, there is no way to specify optional elements in the date format. There are a couple of optional parts in the RFC 822 specification which is breaking the date parser. If nothing works out, I'd probably have to write a custom parser to obey the specs.

例如,日期名称在规范中是可选的。所以这两个日期都是有效的:

For example, the day name is optional in the spec. So both these dates are valid:

Tue,01 Dec 2009 08:48:25 +0000 被解析格式 EEE,dd MMM yyyy HH:mm:ss z
01 Dec 2009 08:48:25 +0000 被解析为格式 dd MMM yyyy HH:mm:ss z

Tue, 01 Dec 2009 08:48:25 +0000 is parsed with the format EEE, dd MMM yyyy HH:mm:ss z 01 Dec 2009 08:48:25 +0000 is parsed with the format dd MMM yyyy HH:mm:ss z

这是我目前使用:

+ (NSDateFormatter *)rfc822Formatter {
    static NSDateFormatter *formatter = nil;
    if (formatter == nil) {
        formatter = [[NSDateFormatter alloc] init];
        NSLocale *enUS = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
        [formatter setLocale:enUS];
        [enUS release];
        [formatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss z"];
    }
    return formatter;
}

+ (NSDate *)dateFromRFC822:(NSString *)date {
    NSDateFormatter *formatter = [NSDate rfc822Formatter];
    return [formatter dateFromString:date];
}

并解析日期如下:

self.entry.published = [NSDate dateFromRFC822:self.currentString];

一种方法是尝试两种格式,并采取任何返回非空值。但是,规格(日名称和秒)中有两个可选部分,并且将有4种可能的组合。仍然没有太糟糕,但是它有点黑客。

One way is to try both formats, and take whatever returns non null value. However, there are two optional parts in the spec (day name and seconds) and there would be 4 possible combinations. Still not too bad, but it's a bit hacky.

推荐答案

在决定使用哪个格式化程序之前,先计算突出字符的数量。例如,你给出的两个不同数量的逗号和空格。如果没有已知的格式匹配计数,那么您甚至不知道甚至尝试将其解析为日期。

Count the number of salient characters before deciding which formatter to use. For example, the two you give have different numbers of commas and spaces. If no known format matches the counts, then you known not even to try parsing it as a date.

这篇关于使用NSDateFormatter解析RFC 822日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆