Last day of quarter adjuster

Example shows how to find the last day of quarter using Java 8 adjuster. The TemporalAdjuster interface, in the java.time.temporal package, adjustInto method accepts a temporal value and returns an adjusted value. The adjustInto method will evaluate the passed-in date to determine quarter and then return the last day of the quarter.

Setup

public class LastDayOfQuarter implements TemporalAdjuster {

    @Override
    public Temporal adjustInto(Temporal temporal) {

        int currentQuarter = YearMonth.from(temporal).get(
                IsoFields.QUARTER_OF_YEAR);

        if (currentQuarter == 1) {

            return LocalDate.from(temporal).withMonth(Month.MARCH.getValue())
                    .with(TemporalAdjusters.lastDayOfMonth());

        } else if (currentQuarter == 2) {

            return LocalDate.from(temporal).withMonth(Month.JUNE.getValue())
                    .with(TemporalAdjusters.lastDayOfMonth());

        } else if (currentQuarter == 3) {

            return LocalDate.from(temporal)
                    .withMonth(Month.SEPTEMBER.getValue())
                    .with(TemporalAdjusters.lastDayOfMonth());

        } else {

            return LocalDate.from(temporal).with(
                    TemporalAdjusters.lastDayOfYear());
        }

    }
}

Last day of first quarter

@Test
public void first_quarter_last_day() {

    LocalDate date = LocalDate.of(2009, Month.FEBRUARY, 1);

    LocalDate firstQuarter = date.with(new LastDayOfQuarter());

    assertEquals(LocalDate.of(2009, Month.MARCH, 31), firstQuarter);
}

Last day of second quarter

@Test
public void second_quarter_last_day() {

    LocalDate date = LocalDate.of(2009, Month.MAY, 1);

    LocalDate secondQuarter = date.with(new LastDayOfQuarter());

    assertEquals(LocalDate.of(2009, Month.JUNE, 30), secondQuarter);
}

Last day of third quarter

@Test
public void third_quarter_last_day() {

    LocalDate date = LocalDate.of(2009, Month.AUGUST, 1);

    LocalDate thirdQuarter = date.with(new LastDayOfQuarter());

    assertEquals(LocalDate.of(2009, Month.SEPTEMBER, 30), thirdQuarter);
}

Last day of fourth quarter

@Test
public void fourth_quarter_first_day() {

    LocalDate date = LocalDate.of(2009, Month.NOVEMBER, 1);

    LocalDate fourthQuarter = date.with(new LastDayOfQuarter());

    assertEquals(LocalDate.of(2009, Month.DECEMBER, 31), fourthQuarter);
}