如何在考虑 startDate 和 endDate 属于不同月份时生成日期列表?

How to generate list of dates taking into consideration the month of startDate and endDate when they fall in different month?

假设我有 startDateendDatecurrentDate

1. 我想忽略 startDateendDatecurrentDate 月之外的实例。

2.startDatecurrentDate 是同一个月但 endDate 的月份大于 currentDate 时,则在 startDatestartDate 月的结束日。

3.endDatecurrentDate 同月且 startDate 小于 currentDate 月时,则在 endDatecurrentDate

的第一天

我需要一些帮助来处理这个问题。

谢谢

首先让我们创建一个方法,在给定开始日期和结束日期的情况下创建一系列日期。此方法利用 LocalDate 中的 plusDays 在 while 循环中生成日期。

public static List<LocalDate> makeDateInterval(LocalDate startDate, LocalDate endDate) {
    List<LocalDate> list = new ArrayList<>();
    if (startDate.isAfter(endDate)) {
        return list;
    }
    LocalDate nextDate = startDate;

    while (nextDate.isBefore(endDate)) {
        list.add(nextDate);
        nextDate = nextDate.plusDays(1);
    }
    list.add(endDate);
    return list;
}

为了弄清楚开始日期和结束日期是什么,我们需要一个简单的逻辑来比较给定日期的月份,如果我们有一个有效的间隔,我们就调用上面的方法

public static List<LocalDate> buildDateRange(LocalDate startDate, LocalDate endDate, LocalDate currentDate) {
    LocalDate firstDate = null;
    LocalDate secondDate = null;

    if (startDate.getMonth() == currentDate.getMonth()) {
        firstDate = startDate;
        secondDate = currentDate;
    }

    if (endDate.getMonth() == currentDate.getMonth()) {
        secondDate = endDate;
        if (firstDate == null) {
            firstDate = currentDate;
        }
    }

    if (firstDate == null || secondDate == null) {
        return new ArrayList<>(); //No valid interval, return empty list
    }

    return makeDateInterval(firstDate, secondDate);
}

今天 2 月 1 日进行简单测试

public static void main(String[] args) {
   LocalDate now = LocalDate.now();
   LocalDate start = now.minusDays(5);
   LocalDate end = now.plusDays(5);

   System.out.println("Now: " + now + ", start: " + start + ", end: " +end);
   List<LocalDate> list = buildDateRange(start, end, now);

   for (LocalDate d : list) {
       System.out.println(d);
   }
}

生成以下输出

Now: 2019-02-01, start: 2019-01-27, end: 2019-02-06
2019-02-01
2019-02-02
2019-02-03
2019-02-04
2019-02-05
2019-02-06