Predefined year adjusters

Example shows predefined year adjusters available in Java 8. The TemporalAdjuster interface, in the java.time.temporal package, adjustInto method accepts a temporal value and returns an adjusted value.

First day of next year

The "first day of next year" adjuster will return a new date set to the first day of the next year. In this example, we will set the LocalDate to August 11, 1971 and find January 1, 1972 by using TemporalAdjusters.firstDayOfNextYear.

@Test
public void first_day_of_next_year() {

    LocalDate date = LocalDate.of(1971, Month.AUGUST, 11);

    LocalDate firstDayOfMonth = date.with(TemporalAdjusters
            .firstDayOfNextYear());

    assertEquals(LocalDate.of(1972, Month.JANUARY, 1), firstDayOfMonth);
}

First day of year

The "first day of year" adjuster will return a new date set to the first day of the current year. We will set LocalDate to September 11, 1971 and find January 1, 1971 by using TemporalAdjusters.firstDayOfYear.

@Test
public void first_day_of_year() {

    LocalDate date = LocalDate.of(1971, Month.SEPTEMBER, 11);

    LocalDate firstDayOfMonth = date.with(TemporalAdjusters
            .firstDayOfYear());

    assertEquals(LocalDate.of(1971, Month.JANUARY, 1), firstDayOfMonth);
}

Last day of year

The "last day of year" adjuster will return a new date set to the last day of the current year. We will set the LocalDate to October 11, 1971 and find December 31, 1971 by using TemporalAdjusters.lastDayOfYear.

@Test
public void last_day_of_year() {

    LocalDate date = LocalDate.of(1971, Month.OCTOBER, 11);

    LocalDate firstDayOfMonth = date
            .with(TemporalAdjusters.lastDayOfYear());

    assertEquals(LocalDate.of(1971, Month.DECEMBER, 31), firstDayOfMonth);
}