日期的格式化與解析
在不同日期表示法之間工作時,日期的格式化與解析相當重要。這個練習中,你會將日期格式化,並把字串解析成 LocalDate。
所有來自 java.time 的必要類別都已為你匯入。
本練習屬於課程
Java 的輸入/輸出與串流
練習說明
- 取得現在的日期。
- 使用樣式
dd-MM-yyyy定義一個DateTimeFormatter。 - 使用該格式器格式化現在日期。
- 使用定義好的格式器解析一個日期字串。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
public class DateExample {
public static void main(String[] args) {
// Get current date
LocalDate date = ____;
System.out.println("Current date in default format: " + date);
// Define format with pattern dd-MM-yyyy
DateTimeFormatter formatter = DateTimeFormatter.____("dd-MM-yyyy");
// Format and print date
System.out.println(date.____(formatter));
// Parse a text into a string
LocalDate parseDate = LocalDate.____("2025-02-10");
System.out.println("Parse the text into date: " + parseDate);
}
}