gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:38:34 24 4
gpt4 key购买 nike

我有以下方法在 Jan 3, 2022 9:06:16 PM 中生成日期在 JDK-8 上运行时的格式。但是,一旦我将 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 生成相同格式的日期?

最佳答案

日期格式的差异是由 JDK 9 开始的默认语言环境提供程序更改引起的,可以找到更多相关详细信息 here .

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

-Djava.locale.providers=COMPAT

关于java - JDK-11 在日期格式中引入逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70572837/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com