how to get a list of dates between two dates in java

后端 未结 22 1835
余生分开走
余生分开走 2020-11-22 13:24

I want a list of dates between start date and end date.

The result should be a list of all dates including the start and end date.

22条回答
  •  一生所求
    2020-11-22 13:41

    Back in 2010, I suggested to use Joda-Time for that.

    Note that Joda-Time is now in maintenance mode. Since 1.8 (2014), you should use java.time.

    Add one day at a time until reaching the end date:

    int days = Days.daysBetween(startDate, endDate).getDays();
    List dates = new ArrayList(days);  // Set initial capacity to `days`.
    for (int i=0; i < days; i++) {
        LocalDate d = startDate.withFieldAdded(DurationFieldType.days(), i);
        dates.add(d);
    }
    

    It wouldn't be too hard to implement your own iterator to do this as well, that would be even nicer.

提交回复
热议问题