【发布时间】:2021-12-08 21:19:15
【问题描述】:
我需要使用 DateTimeFormatter 将字符串解析为 LocalDate。
有 2 种不同的情况,模式字符串 dMMyy 或 ddMMyy (20320, 020320, 120320) 和模式字符串 ddMMyyyy 或 dMMyyyy (2032020, 02032020, 12032020)。
对于第一种情况,我可以只使用 DateTimeFormatter.ofPattern("dMMyy") 它适用于 5 或 6 位长日期。
@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);
}
对于第二种情况,我认为我可以使用模式“dMMyyyy”,但它只是不解析任何输入字符串。
@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);
}
编辑:
我的问题:有没有办法以解析 7-8 位变体的方式实例化 DateTimeFormatter use DateTimeFormatter.ofPattern?
编辑了问题,以便@user16320675 的答案匹配,因为它解决了我的问题。
【问题讨论】:
-
@user16320675 这似乎有效。你能写一个答案让我接受吗?