Java Data Type How to - Use Temporal adjusters for adjusting the dates








Question

We would like to know how to use Temporal adjusters for adjusting the dates.

Answer

import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.TemporalAdjusters;
//  w w w .  j a  v  a  2  s  .  co  m
public class Main {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();

        // Temporal adjusters for adjusting the dates
        System.out.println("First date of this month= "
                + today.with(TemporalAdjusters.firstDayOfMonth()));
        LocalDate lastDayOfYear = today.with(TemporalAdjusters.lastDayOfYear());
        System.out.println("Last date of this year= " + lastDayOfYear);

        Period period = today.until(lastDayOfYear);
        System.out.println("Period Format= " + period);
        System.out.println("Months remaining in the year= " + period.getMonths());

    }
}

The code above generates the following result.