I have following method that generates the date in Jan 3, 2022 9:06:16 PM
format when runs on JDK-8. However, as soon as I changed my jdk to JDK-11, it generates the date in format Jan 3, 2022, 9:12:28 PM
. So there is a difference of comma after 2022
in the output. My test case is failing due to this mismatch. I need to keep JDK-11 generating the same format in my service method as show below -
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;
}
My Test Method looks like this -
@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);
}
The parse()
fails at index 11 which is exact position of comma in the date format. To my surprise, manually removing the character at index 11 using string builder or string concatenation introduced some non-english value like this - "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;
}
How do I make jdk-11 generate a same formatted date?
DateFormat
,TimeZone
andDate
. Those classes are poorly designed and long outdated, the first in particular notoriously troublesome. Instead useDateTimeFormatter
,ZoneId
andZonedDateTime
, all from java.time, the modern Java date and time API. – Linettelineup