Java Data Type How to - Get first day of Month and first Monday in a month with TemporalAdjuster








Question

We would like to know how to get first day of Month and first Monday in a month with TemporalAdjuster.

Answer

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.TemporalAdjusters;
// w w w  .  j a  va2  s .  c o  m
public class Main {

  public static void main(String[] args) {
    LocalDate date = LocalDate.of(2014, Month.JULY, 16);
    System.out.println(date);

    LocalDate firstDayOfJuly = date.with(TemporalAdjusters.firstDayOfMonth()); // 2014-07-01
    System.out.println(firstDayOfJuly);

    LocalDate dateOfFirstMonday = date.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)); // 2014-07-07
    System.out.println(dateOfFirstMonday);

  }
}

The code above generates the following result.