I need to parse Strings to LocalDate using DateTimeFormatter.
There are 2 different cases, Strings of pattern dMMyy or ddMMyy (20320, 020320, 120320) and Strings of pattern ddMMyyyy or dMMyyyy (2032020, 02032020, 12032020).
For the first case i can just use DateTimeFormatter.ofPattern("dMMyy") which works with 5 or 6 digits long dates.
@Test
public void dateConversionyy() {
DateTimeFormatter worksShortd = DateTimeFormatter.ofPattern("dMMyy");
DateTimeFormatter worksShortdd = DateTimeFormatter.ofPattern("ddMMyy");
String longString = "120320";
String leadingZeroString = "020320";
String shortString = "20320";
LocalDate res = LocalDate.parse(longString, worksShortd);
assertNotNull(res);
LocalDate res2 = LocalDate.parse(longString, worksShortdd);
assertNotNull(res2);
assertEquals(res, res2);
LocalDate res3 = LocalDate.parse(shortString, worksShortd);
assertNotNull(res3);
LocalDate res4 = LocalDate.parse(leadingZeroString, worksShortd);
assertNotNull(res4);
assertEquals(res3, res4);
LocalDate res5 = LocalDate.parse(leadingZeroString, worksShortdd);
assertNotNull(res);
assertEquals(res3, res5);
}
For the second case i thought i could use pattern "dMMyyyy", but it just dont parse any input String.
@Test
public void dateConversionyyyy() {
LocalDate res;
DateTimeFormatter failsLong = DateTimeFormatter.ofPattern("dMMyyyy");
DateTimeFormatter worksLong = DateTimeFormatter.ofPattern("ddMMyyyy");
String longString = "13082020";
String shortString = "3082020";
boolean notParsed1 = false;
try {
LocalDate.parse(longString, failsLong);
} catch (DateTimeParseException e) {
notParsed1 = true;
}
assertTrue(notParsed1);
res = LocalDate.parse(longString, worksLong);
assertNotNull(res);
boolean notParsed2 = false;
try {
LocalDate.parse(shortString, failsLong);
} catch (DateTimeParseException e) {
notParsed2 = true;
}
assertTrue(notParsed2);
}
Edit:
My Question: Is there a way to instantiate DateTimeFormatter use DateTimeFormatter.ofPattern in a way that would parse the 7-8 digits variant?
Edited the Question so that @user16320675 answer matches, as it solved my problem.