從日期擷取月份與年份
你正在追蹤電子商品門市的每月庫存。請套用日期標準化,從每個日期中擷取月份與年份!
所需的套件(例如 LocalDate 與 DateTimeFormatter)已經為你匯入。
本練習屬於課程
使用 Java 進行資料清理
練習說明
- 指定
date1的格式為個位數的月/日。 - 指定
date2的格式為補零的月/日。 - 從
date1與date2擷取月份與年份。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
public class DateStandardizationExample {
public static void main(String[] args) {
// Specify the format of date1 with single-digit month/day
LocalDate date1 = LocalDate.parse("1/1/23", DateTimeFormatter.ofPattern("____/____/____"));
// Specify the format of date2 with zero-padded month/day
LocalDate date2 = LocalDate.parse("07-01-2023", DateTimeFormatter.ofPattern("____-____-____"));
// Extract the month and year from date1 and date2
System.out.println("Month and year of " + date1 + ": " + date1.____() + " " + date1.____());
System.out.println("Month and year of " + date2 + ": " + date2.____() + " " + date2.____());
}
}