日付の標準化
電子機器の在庫管理で製造日を記録していますが、日付の形式がバラバラです。日付の形式を標準化し、表示用にフォーマットしましょう。
| 製品名 | 製造日 |
|---|---|
| Laptop | 3/1/25 |
| Smartphone | 04-01-2025 |
| Monitor | 2025.06.01 |
LocalDate や DateTimeFormatter などの必要なパッケージは、あらかじめインポートされています。
この演習はコースの一部です
Java によるデータクリーニング
演習の手順
- 入力される日付のフォーマットを指定しましょう。
datesの各文字列を日付として解析しましょう。manufacturingDateを、月の完全な名前・先頭ゼロなしの日・4 桁の年の形式で表示しましょう。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
public class DateStandardizationExample {
public static void main(String[] args) {
String[] dates = { "3/1/25", "04-01-2025", "2025.06.01" };
// Specify the input date formats
DateTimeFormatter[] formatters = {
____.____("M/d/yy"),
____.____("MM-dd-yyyy"),
____.____("yyyy.MM.dd")
};
System.out.println("Standardized manufacturing dates:");
for (int i = 0; i < dates.length; i++) {
// Parse each string in dates as a date
LocalDate productDate = ____.____(dates[i], formatters[i]);
System.out.println("Date " + dates[i] + " is standardized as " + productDate);
}
LocalDate manufacturingDate = LocalDate.parse("2023-01-01");
// Display date as full month name, day without leading zeros, and full year
DateTimeFormatter displayFormat = DateTimeFormatter.ofPattern("____ ____, ____");
String formattedDate = manufacturingDate.format(displayFormat);
System.out.println("\nFormatted manufacturing date: " + formattedDate);
}
}