with() Methods

Description

To change a field in a datetime object we can use a method with a prefix with.

withXXX() method returns a copy of an object with the specified field changed since most of the objects in Date Time API are immutable.

Example

The following code shows how to get a LocalDate from another LocalDate with the year changed:


import java.time.LocalDate;
import java.time.Month;
//  w  ww.  j  a  v  a  2s .  c  om
public class Main {
  public static void main(String[] args) {
    LocalDate localDate1  = LocalDate.of(2014, Month.MAY,  2);
    System.out.println(localDate1);
    
    LocalDate localDate2  = localDate1.withYear(2015);
    System.out.println(localDate2);
    
    LocalDate localDate3  = localDate1.withYear(2014).withMonth(7);
    System.out.println(localDate3);
    
  }
}

The code above generates the following result.





















Home »
  Java Date Time »
    Tutorial »




Java Date Time Tutorial