共計 814 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Java 中,可以使用 java.time.LocalDate
類來處理日期。下面是一個示例代碼,演示如何獲取兩個日期之間的所有日期:
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
public class Main {public static void main(String[] args) {LocalDate startDate = LocalDate.of(2022, 1, 1);
LocalDate endDate = LocalDate.of(2022, 1, 10);
List<LocalDate> allDates = new ArrayList<>();
LocalDate currentDate = startDate;
while (currentDate.isBefore(endDate) || currentDate.isEqual(endDate)) {allDates.add(currentDate);
currentDate = currentDate.plusDays(1);
}
for (LocalDate date : allDates) {System.out.println(date);
}
}
}
在上面的示例中,startDate
和 endDate
分別表示要獲取的日期范圍的起始日期和結束日期。allDates
是一個列表,用于存儲所有的日期。currentDate
是一個當前日期變量,初始值為起始日期。
使用 while
循環,我們在 currentDate
小于等于結束日期時,將當前日期添加到 allDates
列表中,并將 currentDate
增加一天。最后,我們遍歷 allDates
列表,并打印每個日期。
輸出將是從 2022 年 1 月 1 日到 2022 年 1 月 10 日的所有日期。
丸趣 TV 網 – 提供最優質的資源集合!
正文完