日付のフォーマットとパース
さまざまな表現の日付を扱うには、フォーマットとパースが不可欠です。この演習では、日付をフォーマットし、文字列を 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);
}
}