Adjusting Dates and Times - Java Date Time

Java examples for Date Time:Date Time Adjust

Description

Adjusting Dates and Times

Demo Code

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;

public class Main {
  public static void main(String[] args) {
    LocalDate today = LocalDate.now();
    System.out.println("Today: " + today);

    // Use a DateAdjuster to adjust today's date to the next Monday
    LocalDate nextMonday = today.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
    System.out.println("Next Monday: " + nextMonday);

    // Use a DateAdjuster to adjust today's date to the last day of month
    LocalDate lastDayOfMonth = today.with(TemporalAdjusters.lastDayOfMonth());
    System.out.println("Last day of month: " + lastDayOfMonth);

    // Create an adjuster that retruns a date after 3 months and 2 days
    TemporalAdjuster adjuster = TemporalAdjusters.ofDateAdjuster(
        (LocalDate date) -> date.plusMonths(3).plusDays(2));
    LocalDate dayAfter3Mon2Day = today.with(adjuster);
    System.out.println("Date after 3 months and 2 days: " + dayAfter3Mon2Day);
  }//from w  w w  .  j av  a2s  .  co  m
}

Related Tutorials