Java で2つの日付の間に含まれるすべての日付を取得する方法

Java では、java.time.LocalDate クラスを使用して日付を処理できます。2 つの日付の間のすべての日付を取得する方法を示すサンプル コードを次に示します。

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 <= endDate) {
allDates.add(currentDate);
currentDate = currentDate.plusDays(1);
}
for (Date d: allDates) {
System.out.println(d);
}

出力は、2022年1月1日から2022年1月10日までの全ての日付が出力されます。

bannerAds