Java.time - 解析月份名称无效

Java.time - Parsing a month's name not working

我必须处理从 Java 中的外部 API 接收到的时间戳。日期时间格式的示例如下所示:

"May 9, 2018 5:32:31 PM CEST"

DateTimeFormatter#Predefined Formatters 的文档中查找信息后,我发现此格式未包含在预定义格式中。 所以我继续使用 DateTimeFormatter#Patterns for Formatting and Parsing 定义我自己的 DateTimeFormatter 并收到以下错误消息:

Exception in thread "main" java.time.format.DateTimeParseException: Text 'May 9, 2018 5:32:31 PM CEST' could not be parsed at index 0

所以我去了 "The Java Tutorials",发现他们解析月份名称的示例在我的程序中不起作用...

来自The Java Tutorials Parsing and Formatting

String input = "Mar 23 1994";
    try {
        DateTimeFormatter formatter =
                          DateTimeFormatter.ofPattern("MMM d yyyy");
        LocalDate date = LocalDate.parse(input, formatter);
        System.out.printf("%s%n", date);
    }
    catch (DateTimeParseException exc) {
        System.out.printf("%s is not parsable!%n", input);
        throw exc;      // Rethrow the exception.
    }

这会抛出相同的错误消息,因为在到达月份名称时解析失败...所以我的问题是如何使用 java.time 包从上面解析日期时间字符串。

的答案在我的机器上运行正常。 (所以 MMM 模式有效,但从字符串解析时无效)

感谢您的帮助!

日期字符串将使用默认语言环境进行解析(Locale.GERMAN 也许?)。

如果文字不是相应的语言,您必须指定正确的Locale,例如:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy").withLocale(Locale.ENGLISH);