我如何解析 "Thu, 8 Dece 2016 09:54:00 GMT" 与月份中额外的 'e'?

How do I parse "Thu, 8 Dece 2016 09:54:00 GMT" with the extra 'e' in the month?

我能够解析所有类型的日期,但是这个日期在月份中有一个额外的字母。我该如何解析?

我不知道剩下的几个月是怎么来的,但希望它们是有 4 个字母的月份。我正在使用 E, dd MMM yyyy HH:mm:ss z 格式,异常出现在偏移量 10.

// java    
String input = "Thu, 8 Dece 2016 09:54:00 GMT";
String p = "[^.*,\s\d+\s+]+[\s+]";
Pattern pattern = Pattern.compile(p);
Matcher m = pattern.matcher(input);
while (m.find()) {
    String month = m.group().substring(0, 3);
    input = input.replaceFirst(p, month + " ");
}
System.out.println(input); // Thu, 8 Dec 2016 09:54:00 GMT

如果您使用 E, dd MMM yyyy HH:mm:ss Z 格式,您的日期字符串应该类似于 Thu, 08 Dec 2016 19:33:26 +0000。不知道为什么这个月有 4 个字符。在较早的情况下,您可以使用 SimpleDateFormat:

从一种格式转换为另一种格式
try {
    String input = "Thu, 8 Dec 2016 09:54:00 GMT";
    SimpleDateFormat sdf1 = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
    Date date1 = sdf1.parse(input);
    SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
    String date2 = sdf2.format(date1);
    System.out.println("Parsed : " + date2);  //Parsed : 08-12-2016 09:54:00
} catch (Exception e) {
    System.out.println(e);
}

您可以自定义 SimpleDateFormat 使用的 DateFormatSymbols

DateFormatSymbols symbols = DateFormatSymbols.getInstance();

String[] months = symbols.getShortMonths();
months[11] = "Dece";
symbols.setShortMonths(months);

DateFormat fmt =
    new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", symbols);

String s = "Thu, 8 Dece 2016 09:54:00 GMT";
Date date = fmt.parse(s);

您也可以使用 Java 8 日期时间 类 来完成它,尽管它有点冗长:

Locale locale = Locale.getDefault();
Map<Long, String> monthNames = new HashMap<>(12);
for (Month month : Month.values()) {
    long value = month.getValue();
    String name = month.getDisplayName(TextStyle.SHORT, locale);
    monthNames.put(value, name);
}

monthNames.put(12L, "Dece");

DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
builder.appendPattern("EEE, d ");
builder.appendText(ChronoField.MONTH_OF_YEAR, monthNames);
builder.appendPattern(" yyyy HH:mm:ss z");

DateTimeFormatter formatter = builder.toFormatter();

String s = "Thu, 8 Dece 2016 09:54:00 GMT";
ZonedDateTime dateTime = ZonedDateTime.parse(s, formatter);
Date date = Date.from(dateTime.toInstant());