First day of quarter adjuster

Example shows how to find the first 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 first day of the quarter.

Setup

public class FirstDayOfQuarter 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).with(
                    TemporalAdjusters.firstDayOfYear());

        } else if (currentQuarter == 2) {

            return LocalDate.from(temporal).withMonth(Month.APRIL.getValue())
                    .with(TemporalAdjusters.firstDayOfMonth());

        } else if (currentQuarter == 3) {

            return LocalDate.from(temporal).withMonth(Month.JULY.getValue())
                    .with(TemporalAdjusters.firstDayOfMonth());

        } else {

            return LocalDate.from(temporal).withMonth(Month.OCTOBER.getValue())
                    .with(TemporalAdjusters.firstDayOfMonth());

        }
    }
}

First day of first quarter

@Test
public void first_quarter_first_day () {

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

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

    assertEquals(
            LocalDate.of(2009, Month.JANUARY, 1),
            firstQuarter);
}

First day of second quarter

@Test
public void second_quarter_first_day () {

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

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

    assertEquals(
            LocalDate.of(2009, Month.APRIL, 1),
            secondQuarter);
}

First day of third quarter

@Test
public void third_quarter_first_day () {

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

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

    assertEquals(
            LocalDate.of(2009, Month.JULY, 1),
            thirdQuarter);
}

First day of fourth quarter

@Test
public void fourth_quarter_first_day () {

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

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

    assertEquals(
            LocalDate.of(2009, Month.OCTOBER, 1),
            fourthQuarter);
}