1 回答

TA貢獻1784條經驗 獲得超7個贊
是的,老的,SimpleDateFormat解析的時候麻煩,一般都不太關注格式模式字符串中模式字母的個數。DateTimeFormatter確實如此,這通常是一個優點,因為它可以更好地驗證字符串。MM月份需要兩位數。yy需要兩位數的年份(例如 2019 年為 19)。由于您需要能夠解析一位數字的月份、月份中的某一天以及四位數字的年份,因此我建議我們修改格式模式字符串以準確地說明DateTimeFormatter這一點。我正在改變MM到M,dd到d,yy到y。這將導致DateTimeFormatter不必擔心位數(一個字母基本上意味著至少一位數字)。
Map<String, String> formattedDates = Map.of(
"MM dd yy", "8 12 2019",
"dd MM yy", "4 5 2007",
"yy dd MM", "2001 10 8");
for (Map.Entry<String, String> e : formattedDates.entrySet()) {
String formatPattern = e.getKey();
// Allow any number of digits for each of year, month and day of month
formatPattern = formatPattern.replaceFirst("y+", "y")
.replace("dd", "d")
.replace("MM", "M");
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern(formatPattern);
LocalDate date = LocalDate.parse(e.getValue(), sourceFormatter);
System.out.format("%-11s was parsed into %s%n", e.getValue(), date);
}
該片段的輸出是:
8 12 2019 was parsed into 2019-08-12
4 5 2007 was parsed into 2007-05-04
2001 10 8 was parsed into 2001-08-10
添加回答
舉報