Predefined month adjusters

Example shows predefined month 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 month

The "first day of month" adjuster will return a new date set to the first day of the current month. In our example, we will set the LocalDate to February 11, 1955 and then use the TemporalAdjusters.firstDayOfMonth to find February 1, 1955.

@Test
public void first_day_of_month() {

    LocalDate date = LocalDate.of(1955, Month.FEBRUARY, 11);

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

    assertEquals(LocalDate.of(1955, Month.FEBRUARY, 1), firstDayOfMonth);
}

First day of next month

The "first day of next month" adjuster will return a new date set to the first day of the next month. In our example, we will set LocalDate to March 11, 1955 and then using TemporalAdjusters.firstDayOfNextMonth to find April 1, 1955.

@Test
public void first_day_of_next_month() {

    LocalDate date = LocalDate.of(1955, Month.MARCH, 11);

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

    assertEquals(LocalDate.of(1955, Month.APRIL, 1), firstDayOfMonth);
}

First Monday in May

The first day in month adjuster will return a new date in the same month with the first matching day-of-week. In this example, we will find the "First Monday in May" by setting the LocalDate to May 11, 1955 and then using TemporalAdjusters.firstInMonth passing in DayOfWeek.MONDAY.

@Test
public void first_in_month() {

    LocalDate date = LocalDate.of(1955, Month.MAY, 11);

    LocalDate firstMondayInMonth = date.with(TemporalAdjusters
            .firstInMonth(DayOfWeek.MONDAY));

    assertEquals(LocalDate.of(1955, Month.MAY, 2), firstMondayInMonth);
}

Last day of month

The "last day of month" adjuster will return a new date set to the last day of the current month. In our example, we will set the LocalDate to June 11, 1955 and then using TemporalAdjusters.lastDayOfMonth to find June 30, 1955.

@Test
public void last_day_of_month() {

    LocalDate date = LocalDate.of(1955, Month.JUNE, 11);

    LocalDate firstMondayInMonth = date.with(TemporalAdjusters
            .lastDayOfMonth());

    assertEquals(LocalDate.of(1955, Month.JUNE, 30), firstMondayInMonth);
}

Last Tuesday in month

The last day in month adjuster will return a new date in the same month with the last matching day-of-week. For example we will find the "Last Tuesday in July" by first setting the LocalDate to July 11, 1955 and then using TemporalAdjusters.lastInMonth passing in DayOfWeek.TUESDAY.

@Test
public void last_in_month() {

    LocalDate date = LocalDate.of(1955, Month.JULY, 11);

    LocalDate firstMondayInMonth = date.with(TemporalAdjusters
            .lastInMonth(DayOfWeek.TUESDAY));

    assertEquals(LocalDate.of(1955, Month.JULY, 26), firstMondayInMonth);
}