Java.time - 解析月份的名称不起作用



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

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

在DateTimeFormatter#Predefined Formatters的文档中查找信息后,我发现此格式未作为预定义格式包含。因此,我继续使用DateTimeFormatter#格式化和解析模式定义我自己的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

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

从Java教程解析和格式化:

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包解析上面的datetimeString。

这个问题的答案在我的机器上运行正常。(因此MMM模式正在工作,但在从字符串进行解析时不起作用(

谢谢你的帮助!

日期字符串将使用默认的Locale(可能是Locale.GERMAN?(进行解析。

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

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

最新更新