Search code examples
javadatejava-timeperiod

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?


Solution

  • 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);
        }
    }