下面的方法是在JDK-8上运行时生成Jan 3, 2022 9:06:16 PM格式的日期。但是,一旦我将jdk更改为JDK-11,它就会生成格式为Jan 3, 2022, 9:12:28 PM的日期。因此,comma after 2022的输出是不同的。由于这种不匹配,我的测试用例失败了。我需要让JDK-11在我的服务方法中生成如下所示的相同格式-
private DateFormat getLocaleDateFormat(@Nullable final Locale locale, @Nonnull final TimeZone timeZone) {
final DateFormat localDf;
if (locale == null) {
localDf = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
} else {
localDf = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale);
}
final String timeZoneOffsetString = DateUtils.getTimeZoneOffset(timeZone.getRawOffset(), true);
final String localTimeZoneStr = "GMT" + timeZoneOffsetString;
final TimeZone localTz = TimeZone.getTimeZone(localTimeZoneStr);
localDf.setTimeZone(localTz);
return localDf;
}我的测试方法是这样的-
@Test
public void canGetAuditReportWithTimestampLocalized() throws ParseException {
/* All parse operations will fail in case of wrong value */
String localDateValue = aGetAuditReportRequest().withHeader(HttpHeaders.ACCEPT_LANGUAGE.toString(), "en-US,en")
.getNow(ReportsTable.class).getData().get(0).get(0);
SimpleDateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.US)
.parse(localDateValue);
}parse()在索引11处失败,这是逗号在日期格式中的确切位置。令我惊讶的是,使用字符串生成器或字符串连接手动删除索引11处的字符时,引入了一些非英语值,如- "2022年1月3日 下午11:35:57"。
public Date parse(String source) throws ParseException
{
ParsePosition pos = new ParsePosition(0);
Date result = parse(source, pos);
if (pos.index == 0)
throw new ParseException("Unparseable date: \"" + source + "\"" ,
pos.errorIndex);
return result;
}如何使jdk-11生成相同的格式化日期?
发布于 2022-10-18 21:18:22
日期格式上的差异是由启动JDK 9的默认区域设置提供程序更改造成的,有关该更改的更多详细信息可以找到这里。
通过设置下一个选项,可以在JDK 11中启用JDK 8兼容的行为:
-Djava.locale.providers=COMPAThttps://stackoverflow.com/questions/70572837
复制相似问题