Ensure joda compatibility in custom date formats (#38171)

If custom date formats are used, there may be combinations that the new
performat DateFormatters.from() method has not covered yet. This adds a
few such corner cases and ensures the tests are correctly commented
out.
This commit is contained in:
Alexander Reelsen 2019-02-01 15:42:56 +01:00 committed by GitHub
parent 66e4fb4fb6
commit 35ed137684
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 5 deletions

View File

@ -1604,13 +1604,16 @@ public class DateFormatters {
} else if (isLocalDateSet) {
return localDate.atStartOfDay(zoneId);
} else if (isLocalTimeSet) {
return of(LOCALDATE_EPOCH, localTime, zoneId);
return of(getLocaldate(accessor), localTime, zoneId);
} else if (accessor.isSupported(ChronoField.YEAR)) {
if (accessor.isSupported(MONTH_OF_YEAR)) {
return getFirstOfMonth(accessor).atStartOfDay(zoneId);
} else {
return Year.of(accessor.get(ChronoField.YEAR)).atDay(1).atStartOfDay(zoneId);
}
} else if (accessor.isSupported(MONTH_OF_YEAR)) {
// missing year, falling back to the epoch and then filling
return getLocaldate(accessor).atStartOfDay(zoneId);
} else if (accessor.isSupported(WeekFields.ISO.weekBasedYear())) {
if (accessor.isSupported(WeekFields.ISO.weekOfWeekBasedYear())) {
return Year.of(accessor.get(WeekFields.ISO.weekBasedYear()))
@ -1630,6 +1633,18 @@ public class DateFormatters {
throw new IllegalArgumentException("temporal accessor [" + accessor + "] cannot be converted to zoned date time");
}
private static LocalDate getLocaldate(TemporalAccessor accessor) {
if (accessor.isSupported(MONTH_OF_YEAR)) {
if (accessor.isSupported(DAY_OF_MONTH)) {
return LocalDate.of(1970, accessor.get(MONTH_OF_YEAR), accessor.get(DAY_OF_MONTH));
} else {
return LocalDate.of(1970, accessor.get(MONTH_OF_YEAR), 1);
}
}
return LOCALDATE_EPOCH;
}
@SuppressForbidden(reason = "ZonedDateTime.of is fine here")
private static ZonedDateTime of(LocalDate localDate, LocalTime localTime, ZoneId zoneId) {
return ZonedDateTime.of(localDate, localTime, zoneId);

View File

@ -62,11 +62,14 @@ public class JavaJodaTimeDuellingTests extends ESTestCase {
formatter3.parse("20181126T121212.123-0830");
}
public void testCustomTimeFormats() {
assertSameDate("2010 12 06 11:05:15", "yyyy dd MM HH:mm:ss");
assertSameDate("12/06", "dd/MM");
assertSameDate("Nov 24 01:29:01 -0800", "MMM dd HH:mm:ss Z");
}
// this test requires tests to run with -Djava.locale.providers=COMPAT in order to work
// public void testCustomTimeFormats() {
// assertSameDate("2010 12 06 11:05:15", "yyyy dd MM HH:mm:ss");
// assertSameDate("12/06", "dd/MM");
// assertSameDate("Nov 24 01:29:01 -0800", "MMM dd HH:mm:ss Z");
// public void testCustomLocales() {
//
// // also ensure that locale based dates are the same
// assertSameDate("Di., 05 Dez. 2000 02:55:00 -0800", "E, d MMM yyyy HH:mm:ss Z", LocaleUtils.parse("de"));