Java-从2个日期开始按月创建日期组

时间:2018-10-25 08:40:43

标签: java date java-time localdate

使用Java 8

目标

从两个日期(例如:firstDay 2018-09-01和lastDay 2018-11-10),我想创建两个由month创建的firstDay和lastDay数组。例如:

List<LocalDate> firstDays = [2018-09-01,2018-10-01,2018-11-01]
List<LocalDate> lastDays = [2018-09-30, 2018-10-31,2018-11-10]

最终,我希望这种方法也可以应用多年(例如:firstDay 2018-12-10和lastDay 2019-01-06)。

问题

我现在不使用什么来实现该目标。我还在搜寻。请问你能帮帮我吗?

3 个答案:

答案 0 :(得分:2)

您可以像这样使用plusMonth

LocalDate firstDay = LocalDate.parse("2018-09-01");
LocalDate lastDay = LocalDate.parse("2018-11-10");

Long timeBetween = ChronoUnit.MONTHS.between(firstDay, lastDay);

// First day of firstDays is not changeable so add it like it is
List<LocalDate> firstDays = new ArrayList<>(Arrays.asList(firstDay));

// Generate the dates between the start and end date
firstDays.addAll(LongStream.rangeClosed(1, timeBetween)
        .mapToObj(f -> firstDay.withDayOfMonth(1).plusMonths(f))
        .collect(Collectors.toList()));

// For the lastDays, generate the dates
List<LocalDate> lastDays = LongStream.range(0, timeBetween)
        .mapToObj(f -> {
            LocalDate newDate = firstDay.plusMonths(f);
            return newDate.withDayOfMonth(newDate.lengthOfMonth());
        }).collect(Collectors.toList());
// Last day of lastDays is not changeable so add it like it is
lastDays.add(lastDay);

输出

[2018-09-01, 2018-10-01, 2018-11-01]
[2018-09-30, 2018-10-31, 2018-11-10]

答案 1 :(得分:2)

以迭代的方式处理边缘情况:

LocalDate startDate = LocalDate.of(2018, 9, 1);
LocalDate endDate = LocalDate.of(2018, 11, 10);

List<LocalDate> firstDays = new ArrayList<>();
List<LocalDate> lastDays = new ArrayList<>();

LocalDate firstOfMonth = startDate.withDayOfMonth(1);
LocalDate lastOfMonth = startDate.withDayOfMonth(startDate.lengthOfMonth());

while (firstOfMonth.isBefore(endDate)) {
    firstDays.add(firstOfMonth.isBefore(startDate) ? startDate : firstOfMonth);
    lastDays.add(endDate.isBefore(lastOfMonth) ? endDate : lastOfMonth);

    firstOfMonth = firstOfMonth.plus(1, ChronoUnit.MONTHS);
    lastOfMonth = firstOfMonth.withDayOfMonth(firstOfMonth.lengthOfMonth());
}

System.out.println(firstDays);
System.out.println(lastDays);

输出:

[2018-09-01, 2018-10-01, 2018-11-01]
[2018-09-30, 2018-10-31, 2018-11-10]

答案 2 :(得分:0)

已经有两个很好的答案。让我看看我是否还能设计出一些精美的东西。

仅创建一个对象列表

首先,我建议您不要两个列表。这里是一种反模式:Anti-pattern: parallel collections。由于每个第一天都属于另一个列表中相应的最后一天,所以将它们放在一起,一切都会变得更加方便,并且更不会出错。为此,您可以使用一些库类或设计自己的库类:

public class DateInterval {

    LocalDate firstDay;
    LocalDate lastDay;

    public DateInterval(LocalDate firstDay, LocalDate lastDay) {
        if (lastDay.isBefore(firstDay)) {
            throw new IllegalArgumentException("Dates in wrong order");
        }
        this.firstDay = firstDay;
        this.lastDay = lastDay;
    }

    // getters and other stuff

    @Override
    public String toString() {
        return "" + firstDay + " - " + lastDay;
    }

}

使用此类,我们只需要一个列表:

    LocalDate firstDayOverall = LocalDate.of(2018, Month.DECEMBER, 10);
    LocalDate lastDayOverall = LocalDate.of(2019, Month.JANUARY, 6);

    if (lastDayOverall.isBefore(firstDayOverall)) {
        throw new IllegalStateException("Overall dates in wrong order");
    }
    LocalDate firstDayOfLastMonth = lastDayOverall.withDayOfMonth(1);
    LocalDate currentFirstDay = firstDayOverall;
    List<DateInterval> intervals = new ArrayList<>();
    while (currentFirstDay.isBefore(firstDayOfLastMonth)) {
        intervals.add(new DateInterval(currentFirstDay, currentFirstDay.with(TemporalAdjusters.lastDayOfMonth())));
        currentFirstDay = currentFirstDay.withDayOfMonth(1).plusMonths(1);
    }
    intervals.add(new DateInterval(currentFirstDay, lastDayOverall));

    System.out.println("Intervals: " + intervals);

以上代码段的输出为:

  

间隔:[2018-12-10-2018-12-31,2019-01-01-2019-01-06]

同一天的第一天和最后一天的特殊情况是通过完全不循环的循环以及循环后的add来添加单个间隔来处理的。

如果需要两个日期列表

如果您确实坚持两张清单,则两个参数datesUntil的方法很方便:

    List<LocalDate> firstDays = new ArrayList<>();
    firstDays.add(firstDayOverall);
    // first day not to be included in first days
    LocalDate endExclusive = lastDayOverall.withDayOfMonth(1).plusMonths(1);
    List<LocalDate> remainingFirstDays = firstDayOverall.withDayOfMonth(1)
            .plusMonths(1)
            .datesUntil(endExclusive, Period.ofMonths(1))
            .collect(Collectors.toList());
    firstDays.addAll(remainingFirstDays);
    System.out.println("First days: " + firstDays);

    // Calculate last days as the day before each first day except the first
    List<LocalDate> lastDays = remainingFirstDays.stream()
            .map(day -> day.minusDays(1))
            .collect(Collectors.toCollection(ArrayList::new));
    lastDays.add(lastDayOverall);
    System.out.println("Last days:  " + lastDays);

输出:

First days: [2018-12-10, 2019-01-01]
Last days:  [2018-12-31, 2019-01-06]

在旁边

起初,我感到YearMonth类可以提供一个优雅的解决方案。但是我意识到,在第一个月和最后一个月都需要进行特殊处理,因此我认为它所带来的代码不会比上面的代码更加优雅。如果愿意,可以尝试。

相关问题