如何考虑到startDate和endDate在不同月份的月份生成日期列表?

时间:2019-02-01 15:38:14

标签: java localdate

假设我有startDateendDatecurrentDate

1.我想忽略startDateendDate超出currentDate月的情况。

2.startDatecurrentDate处于同一月份,但endDate的月份大于currentDate时,则在{{1 }}到startDate一个月的结束日期。

startDate3.endDate处于同一月份并且currentDate小于startDate个月时,则在{{1}之间创建一个列表}和currentDate

的第一天

我想要一些处理此问题的方法的帮助。

谢谢

1 个答案:

答案 0 :(得分:0)

首先让我们创建一个方法,该方法根据给定的开始日期和结束日期创建日期序列。此方法利用plusDays中的LocalDate在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);
   }
}

生成以下输出

  

现在:2019-02-01,开始:2019-01-27,结束:2019-02-06
  2019-02-01
  2019-02-02
  2019-02-03
  2019-02-04
  2019-02-05
  2019-02-06