JDK-11 在日期格式中引入逗号

Ani*_*ade 5 java simpledateformat java-11

我有以下方法,可以在 JDK-8 上运行时生成日期Jan 3, 2022 9:06:16 PM格式。但是,一旦我将 jdk 更改为 JDK-11,它就会生成格式为 的日期Jan 3, 2022, 9:12:28 PMcomma after 2022因此,输出存在差异。由于这种不匹配,我的测试用例失败了。我需要让 JDK-11 在我的服务方法中生成相同的格式,如下所示 -

\n
    private DateFormat getLocaleDateFormat(@Nullable final Locale locale, @Nonnull final TimeZone timeZone) {\n        final DateFormat localDf;\n        if (locale == null) {\n            localDf = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);\n        } else {\n            localDf = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale);\n        }\n\n        final String timeZoneOffsetString = DateUtils.getTimeZoneOffset(timeZone.getRawOffset(), true);\n        final String localTimeZoneStr = "GMT" + timeZoneOffsetString;\n        final TimeZone localTz = TimeZone.getTimeZone(localTimeZoneStr);\n        localDf.setTimeZone(localTz);\n\n        return localDf;\n    }\n
Run Code Online (Sandbox Code Playgroud)\n

我的测试方法如下 -

\n
@Test\n  public void canGetAuditReportWithTimestampLocalized() throws ParseException {\n    /* All parse operations will fail in case of wrong value */\n      String localDateValue = aGetAuditReportRequest().withHeader(HttpHeaders.ACCEPT_LANGUAGE.toString(), "en-US,en")\n              .getNow(ReportsTable.class).getData().get(0).get(0);\n      SimpleDateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.US)\n              .parse(localDateValue);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

索引 11 处失败parse(),这是日期格式中逗号的确切位置。令我惊讶的是,使用字符串生成器或字符串连接手动删除索引 11 处的字符引入了一些非英语值,例如 - "2022\xe5\xb9\xb41\xe6\x9c\x883\xe6\x97\xa5 \xe4\xb8\x8b\xe5\x8d\x8811:35:57"

\n
    public Date parse(String source) throws ParseException\n    {\n        ParsePosition pos = new ParsePosition(0);\n        Date result = parse(source, pos);\n        if (pos.index == 0)\n            throw new ParseException("Unparseable date: \\"" + source + "\\"" ,\n                pos.errorIndex);\n        return result;\n    }\n
Run Code Online (Sandbox Code Playgroud)\n

如何让jdk-11生成相同格式的日期?

\n

小智 3

日期格式的差异是由 JDK 9 开始的默认区域设置提供程序更改引起的,有关该问题的更多详细信息可以在此处找到。

您可以通过设置下一个选项在 JDK 11 中启用 JDK 8 兼容行为:

-Djava.locale.providers=COMPAT
Run Code Online (Sandbox Code Playgroud)