安卓转换日期时间解析错误(甚至尝试过乔达时间)



我正在解析许多新闻提要,每个项目的pubDate都遵循相同的格式:

周日, 11 六月 2017 18:18:23 +0000

不幸的是,一个提要没有:

周六, 10 六月 2017 12:49:45 EST

我试图使用androids java日期和SimpleDateFormat来解析日期,但没有运气:

try {
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
SimpleDateFormat readDate = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
readDate.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = readDate.parse(rssDateTime);
SimpleDateFormat writeDate = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
writeDate.setTimeZone(tz);
parsedDate = writeDate.format(date);
} catch (ParseException e) {
e.printStackTrace();
}

哪个抛出和错误:

java.text.ParseException: 不可解析的日期:"星期六, 3 Jun 2017 19:53:09 EST" (在偏移量 26)

我也尝试使用joda时间来做到这一点:

DateTime dtUTC = null;
DateTimeZone timezone = DateTimeZone.getDefault();
DateTimeFormatter formatDT = DateTimeFormat.forPattern("EEE, d MMM yyyy HH:mm:ss Z");
DateTime dtRssDateTime = formatDT.parseDateTime(rssDateTime);
DateTime now = new DateTime();
DateTime nowUTC = new LocalDateTime(now).toDateTime(DateTimeZone.UTC);
long instant = now.getMillis();
long instantUTC = nowUTC.getMillis();
long offset = instantUTC - instant;
dtUTC = dtRssDateTime.withZoneRetainFields(timezone);
dtUTC = dtUTC.minusMillis((int) offset);
String returnTimeDate = "";
returnTimeDate = dtUTC.toString(formatDT);

这会引发错误:

由以下原因引起:java.lang.IllegalArgumentException:格式无效:"星期六,10 Jun 2017 12:49:45 EST"在"EST"处格式不正确

以前有人遇到过这种情况吗?

首先,如果你要开始一个新项目,我建议你使用新的日期时间API而不是joda-time(更多内容见下文)。无论如何,这是两者的解决方案。


乔达时间

问题是模式Z是偏移量(以+0000-0100等格式),但字符串EST是时区短名称,由模式z解析(查看 jodatime javadoc 了解更多细节)。

因此,您需要一个具有可选部分的模式,可以同时接收一个或另一个。您可以使用org.joda.time.format.DateTimeFormatterBuilder类执行此操作。

首先,您需要创建 2 个org.joda.time.format.DateTimeParser实例(一个用于Z,另一个用于z),并将它们添加为可选的解析器。然后使用以下代码创建org.joda.time.format.DateTimeFormatter。请注意,我还使用了java.util.Locale,只是为了确保它正确解析工作日和月份名称(因此您不依赖于默认语言环境,该语言环境可能因每个系统/机器而异):

// offset parser (for "+0000")
DateTimeParser offsetParser = new DateTimeFormatterBuilder().appendPattern("Z").toParser();
// timezone name parser (for "EST")
DateTimeParser zoneNameParser = new DateTimeFormatterBuilder().appendPattern("z").toParser();
// formatter for both patterns
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// append common pattern
.appendPattern("EEE, d MMM yyyy HH:mm:ss ")
// optional offset
.appendOptional(offsetParser)
// optional timezone name
.appendOptional(zoneNameParser)
// create formatter (use English Locale to make sure it parses weekdays and month names independent of JVM config)
.toFormatter().withLocale(Locale.ENGLISH)
// make sure the offset "+0000" is parsed
.withOffsetParsed();
// parse the strings
DateTime est = fmt.parseDateTime("Sat, 10 Jun 2017 12:49:45 EST");
DateTime utc = fmt.parseDateTime("Sun, 11 Jun 2017 18:18:23 +0000");
System.out.println(est);
System.out.println(utc);

输出将是:

2017-06-10T12:

49:45.000-04:00
2017-06-11T18:18:23.000Z

如果它们与您预期的不完全一样(或者您仍然收到错误),请参阅下面的注释。


注释

  • 请注意,EST被打印为带有偏移-0400的日期/时间。那是因为EST内部变成了America/New_York时区,现在是夏令时,它的偏移量是-0400(我可以通过做DateTimeZone.forTimeZone(TimeZone.getTimeZone("EST"))来解决这个问题。问题是:这 3 个字母的名字是模棱两可的,不是标准的,而 joda-time 只是假设它们的"默认值"。因此,如果您不期望此时区,并且不想依赖默认值,则可以使用具有自定义值的地图,如下所示:

    // mapping EST to some other timezone (I know it's wrong and Chicago is not EST, it's just an example)
    Map<String, DateTimeZone> map = new LinkedHashMap<>();
    map.put("EST", DateTimeZone.forID("America/Chicago"));
    // parser for my custom map
    DateTimeParser customTimeZoneParser = new DateTimeFormatterBuilder().appendTimeZoneShortName(map).toParser();
    DateTimeFormatter fmt = new DateTimeFormatterBuilder()
    // append common pattern
    .appendPattern("EEE, d MMM yyyy HH:mm:ss ")
    // optional offset
    .appendOptional(offsetParser)
    // optional custom timezone name
    .appendOptional(customTimeZoneParser)
    // optional timezone name (accepts all others that are not in the map)
    .appendOptional(zoneNameParser)
    // create formatter (use English Locale to make sure it parses weekdays and month names independent of JVM config)
    .toFormatter().withLocale(Locale.ENGLISH)
    // make sure the offset "+0000" is parsed
    .withOffsetParsed();
    System.out.println(fmt.parseDateTime("Sat, 10 Jun 2017 12:49:45 EST"));
    

这会将EST解析为America/Chicago(我知道这是错误的,芝加哥不是EST,这只是如何使用地图更改默认值的一个例子),输出将是:

2017-06-10T12:49:45.000-05:00

如果你在上面的第一个代码中遇到错误,你也可以使用它,将EST映射到所需的时区(取决于你使用的jodatime和Java的版本,EST可能不会映射到默认值并引发异常,因此使用自定义映射可以避免这种情况)。


新的日期时间 API

正如@Ole V.V.的评论所说(我昨天没有时间写),joda-time正在被新的Java的日期和时间API所取代,与旧的DateSimpleDateFormat类相比,它要好得多。

如果您使用的是 Java>= 8,则java.time包已经是 JDK 的一部分。对于Java <= 7,有ThreeTen Backport。对于Android,有ThreeTenABP(更多关于如何使用它)。

如果你正在开始一个新项目,请考虑使用新的API而不是joda-time,因为在joda的网站上它说:请注意,Joda-Time被认为是一个基本上"完成"的项目。没有计划进行重大改进。如果使用 Java SE 8,请迁移到 java.time (JSR-310)。

下面的代码适用于这两种情况。唯一的区别是包名(在Java 8中是java.time,在ThreeTen Backport(或Android的ThreeTenABP)中是org.threeten.bp),但类和方法是相同的。

这个想法与jodatime非常相似,但略有不同:

  • 您可以使用可选的节分隔符[]
  • 需要具有自定义时区名称的集合(以将EST映射到某个有效的非明确时区)(因为EST未映射到任何默认值)
  • 使用一个新类:ZonedDateTime,它表示带有时区的日期和时间(因此它涵盖了两种情况)

只是提醒这些类在包java.time(或org.threeten.bp,具体取决于您使用的 Java 版本,如上所述):

// set with custom timezone names
Set<ZoneId> set = new HashSet<>();
// when parsing, ambiguous EST uses to New York
set.add(ZoneId.of("America/New_York"));
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// append pattern, with optional offset (delimited by [])
.appendPattern("EEE, d MMM yyyy HH:mm:ss[ Z]")
// append optional timezone name with custom set for EST
.optionalStart().appendLiteral(" ").appendZoneText(TextStyle.SHORT, set).optionalEnd()
// create formatter using English locale to make sure it parses weekdays and month names correctly
.toFormatter(Locale.ENGLISH);
ZonedDateTime est = ZonedDateTime.parse("Sat, 10 Jun 2017 12:49:45 EST", fmt);
ZonedDateTime utc = ZonedDateTime.parse("Sun, 11 Jun 2017 18:18:23 +0000", fmt);
System.out.println(est); // 2017-06-10T12:49:45-04:00[America/New_York]
System.out.println(utc); // 2017-06-11T18:18:23Z

输出将是:

2017-06-10T12:49:45-04:00[美国/New_York]
2017-06-11T18:18:23Z

请注意,在第一种情况下,EST设置为America/New_York(由自定义集配置)。appendZoneText可以解决问题,使用自定义集中的值来解决不明确的情况。

第二种情况设置为 UTC,因为偏移量为+0000

如果要将第一个对象转换为 UTC,则非常直接:

System.out.println(est.withZoneSameInstant(ZoneOffset.UTC)); // 2017-06-10T16:49:45Z

输出将是转换为 UTC 的纽约日期/时间:

2017-06-10T16:49:45Z

而不是ZoneOffset.UTC,当然你可以使用任何你想要的时区或偏移量(使用ZoneIdZoneOffset类,查看javadoc了解更多细节)。

最新更新