Java Data Type How to - Create a new date with the last day of the same month as the given date








Question

We would like to know how to create a new date with the last day of the same month as the given date.

Answer

   //from w  w w. j  a v  a2  s  .  c  o m
import java.time.LocalDate;

public class Main {
  public static void main(String[] argv) {
    System.out.println(endOfMonth(LocalDate.now()));
  }

  /**
   * Creates a new date object with the last day of the same month as the given
   * date.
   */
  public static LocalDate endOfMonth(LocalDate date) {
    return date.withDayOfMonth(date.lengthOfMonth());
  }

}

The code above generates the following result.