joda-在RSS项目中解析pubDate的时区 [英] joda - parsing time zone of pubDate in RSS item
问题描述
我正在使用Joda解析RSS项目中的pubDate.日期必须为RFC-822格式: http://feed2.w3.org/docs/error/InvalidRFC2822Date.html
I'm parsing pubDate in RSS item using Joda. The date have to be in RFC-822 format: http://feed2.w3.org/docs/error/InvalidRFC2822Date.html
问题在于,当存在类似这样的日期时: 星期三,2002年10月2日格林尼治标准时间13:00:00 我必须使用模式:
The problem is that when there is a date like: Wed, 02 Oct 2002 13:00:00 GMT I have to use pattern:
DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss ZZZ").withLocale(Locale.ENGLISH).withOffsetParsed();
但是它也可以是以下日期: 2002年10月2日,星期三15:00:00 +0200 .在这种情况下,ZZZ无法正常工作,我必须使用一个Z:
But it can be also date like: Wed, 02 Oct 2002 15:00:00 +0200. In this case ZZZ dosen't work, I have to use one Z:
DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss Z").withLocale(Locale.ENGLISH).withOffsetParsed();
如何创建通用解决方案?
How to create universal solution?
推荐答案
我已经使用 JodaTime 2.7 进行了测试,发现了两种方法:
I've made tests with JodaTime 2.7 and found 2 ways to do it:
-
使用
DateTimeFormatterBuilder
的可选解析器:
// create parser for "GMT"
DateTimeParser gmtParser = DateTimeFormat.forPattern("ZZZ").getParser();
// create parser for "+0200"
DateTimeParser offsetParser = DateTimeFormat.forPattern("Z").getParser();
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("EEE, dd MMM yyyy HH:mm:ss ") // common pattern
.appendOptional(gmtParser) // optional parser for GMT
.appendOptional(offsetParser) // optional parser for +0200
.toFormatter().withLocale(Locale.ENGLISH).withOffsetParsed();
DateTimeFormatterBuilder
可以接收用于解析不同输入的解析器数组:
DateTimeFormatterBuilder
can receive an array of parsers that can be used to parse different inputs:
// create array with all possible patterns
DateTimeParser[] parsers = {
DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss Z").getParser(),
DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss ZZZ").getParser()
};
// create a formatter using the parsers array
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(null, parsers) // use parsers array
.toFormatter().withLocale(Locale.ENGLISH).withOffsetParsed();
使用以上任何一种解决方案,formatter
都可以与两个输入一起使用:
Using any of the solutions above, the formatter
will work with both inputs:
System.out.println(formatter.parseDateTime("Wed, 02 Oct 2002 13:00:00 GMT"));
System.out.println(formatter.parseDateTime("Wed, 02 Oct 2002 15:00:00 +0200"));
输出将是:
2002-10-02T13:00:00.000Z
2002-10-02T15:00:00.000+02:00
注意:如果您在所有模式中有一个共同的部分,并且它们之间的差异很小,我相信第一个解决方案会更好.如果模式彼此非常不同,则第二种解决方案更好.但是我也认为这是一个见解,由您选择.
Note: I believe the first solution is better if you have a common part among all patterns and little variation between them. The second solution is better if the patterns are very different from each other. But I also believe it's a matter of opinion and it's up to you to choose.
这篇关于joda-在RSS项目中解析pubDate的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!