3 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個(gè)贊
當(dāng)您知道時(shí),這是微不足道的。一個(gè)模式字母,例如dor M,將接受一位或兩位數(shù)字(或年份最多 9 位數(shù)字)。
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d.M.u");
System.out.println(LocalDate.parse("02.05.2019", dateFormatter));
System.out.println(LocalDate.parse("3.5.2019", dateFormatter));
System.out.println(LocalDate.parse("4.05.2019", dateFormatter));
System.out.println(LocalDate.parse("06.5.2019", dateFormatter));
System.out.println(LocalDate.parse("15.12.2019", dateFormatter));
輸出:
2019-05-02
2019-05-03
2019-05-04
2019-05-06
2019-12-15
我在文檔中搜索了這些信息,但沒有輕易找到。我不認(rèn)為它有據(jù)可查。

TA貢獻(xiàn)1909條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以使用這樣的自定義格式創(chuàng)建 DateTimeFormatter
DateTimeFormatter.ofPattern("d.M.yyyy")
然后,如果日期和月份提供 1 位或 2 位數(shù)字,則您可以解析日期。
String input = "02.5.2019";
LocalDate date = LocalDate.parse(input, DateTimeFormatter.ofPattern("d.M.yyyy"));
我在這里使用了新的 java.time 包中的 LocalDate,所以我假設(shè)您的 Java 版本是最新的。

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超7個(gè)贊
您建議的日期格式應(yīng)該有效——就像這個(gè)測試一樣:
@Test
public void test() throws ParseException {
SimpleDateFormat f = new SimpleDateFormat("d.M.yyyy");
f.parse("7.8.2019");
f.parse("07.08.2019");
f.parse("007.008.002019");
}
相比之下,DateTimeFormatter 不接受年份的前導(dǎo)零,但日和月的前導(dǎo)零不是問題:
@Test
public void test2() throws ParseException {
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
DateTimeFormatter f = builder.appendPattern("d.M.yyyy").toFormatter();
f.parse("7.8.2019");
f.parse("07.08.2019");
f.parse("007.008.2019");
}
添加回答
舉報(bào)