Ojonugwa Jude Ochalifu
Ojonugwa Jude Ochalifu

Reputation: 27256

Get each year in a Period in java

Am trying to get a LocalDate instance for each Year in a Period. For example, for this:

LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(2011, Month.DECEMBER, 19);
Period period = Period.between(birthday, today);

I want 2012-12-19, 2013-12-19, 2014-12-19, 2015-12-19. Given the methods of Period this isn't possible. Is there a way around this? Is it possible using another method?

Upvotes: 4

Views: 879

Answers (2)

JodaStephen
JodaStephen

Reputation: 63465

Care must be taken when looping over dates. The "obvious" solution does not work properly. The solution of Soorapadman will work fine for the date given (the 19th December), but fail if the start date is the 29th February. This is because 1 year later is the 28th, and the date will never return to the 29th February, even when another leap year occurs.

Note that this problem is more pronounced for month addition. A start date of the 31st January will return the sequence 28th February (or 29th), then 28th March 28th April and so on. This is unlikely to be the desired output, which is probably the last date of each month.

The correct strategy is as follows:

public List<LocalDate> datesBetween(LocalDate start, LocalDate end, Period period);
  List<LocalDate> list = new ArrayList<>();
  int multiplier = 1;
  LocalDate current = start;
  while (!current.isAfter(end)) {
    current = start.plus(period.multipliedBy(multiplier);
    list.add(current);
    multiplier++;
  }
  return list;
}

Note how the strategy adds an increasing period to the same start date. The start date is never altered. Using the same start date is critical to retain the correct month length of that date.

Upvotes: 4

soorapadman
soorapadman

Reputation: 4509

You can try like this using Java 8;

    LocalDate start = LocalDate.of(2011, Month.DECEMBER, 19);
    LocalDate end = LocalDate.now();
    while (!start.isAfter(end)) {
        System.out.println(start);
        start = start.plusYears(1);
    }
}

Upvotes: 2

Related Questions