Java - withXXX( ) Methods

Introduction

To change a field of a datetime object, use a method with a prefix like withXXX.

A withXXX() method returns a copy of an object with the specified field changed.

For example, you have a LocalDate object and you want to change its year.

You need to use the withYear(int newYear) method of the LocalDate class.

The following snippet of code shows how to obtain a LocalDate from another LocalDate with the year changed:

LocalDate ld1 = LocalDate.of(2012, Month.MAY, 2); // 2012-05-02
LocalDate ld2 = ld1.withYear(2014); // 2014-05-02

You can obtain a new LocalDate from an existing LocalDate by changing multiple fields by chaining the withXXX() method calls.

The following snippet of code creates a new LocalDate from an existing LocalDate by changing the year and month:

LocalDate ld3 = LocalDate.of(2012, 5, 2); // 2012-05-02
LocalDate ld4 = ld3.withYear(2014).withMonth(7); // 2014-07-02

Demo

import java.time.LocalDate;
public class Main {
  public static void main(String[] args) {
    LocalDate ld3 = LocalDate.of(2012, 5, 2); // 2012-05-02
    LocalDate ld4 = ld3.withYear(2014).withMonth(7); // 2014-07-02
    System.out.println(ld3);//from   w w  w  . j a  va  2 s  .co m
    System.out.println(ld4);
  }
}

Result