Menu

Java LocalDate with() Method

Java LocalDate with() Method

Java with() method is used to get a new date by setting a new value of the specified field. It returns a copy of this date with the specified field set to a new value.

For example, we have a date 2012-10-12 then by specifying DAY_OF_MONTH value as 15, we get a new date 2012-10-15.

Temporal type can be specified with a ChronoField. The supported fields of ChronoField are as follows:

  • DAY_OF_WEEK
  • ALIGNED_DAY_OF_WEEK_IN_MONTH
  • ALIGNED_DAY_OF_WEEK_IN_YEAR
  • DAY_OF_MONTH
  • DAY_OF_YEAR
  • EPOCH_DAY
  • ALIGNED_WEEK_OF_MONTH
  • ALIGNED_WEEK_OF_YEAR
  • MONTH_OF_YEAR
  • PROLEPTIC_MONTH
  • YEAR_OF_ERA
  • YEAR
  • ERA

It takes two arguments first is Temporal type and second is long type. The syntax of the method is given.

Syntax

public LocalDate with(TemporalField field, long newValue)

Parameters:

field - the field to set in the result.

newValue - the new value of the field in the date.

Returns:

It returns a LocalDate based on this with the specified field.

Time for an Example:

Let's take an example to create a new date by setting a new value of a field. Here, we are using with() method to set new day of the date.

import java.time.LocalDate;
import java.time.temporal.ChronoField;
public class DateDemo {
    
    public static void main(String[] args){  
        
        LocalDate localDate = LocalDate.of(2002, 01, 10);
        System.out.println(localDate);
        localDate = localDate.with(ChronoField.DAY_OF_MONTH, 15);
        System.out.println("New Date : "+localDate);
    }
}

Output:

2002-01-10 

New Date : 2002-01-15

Time for another Example:

Let's take an another example to understand the with() method. Here, we are setting a new value of date by specifying the DAY_OF_YEAR value.

import java.time.LocalDate;
import java.time.temporal.ChronoField;
public class DateDemo {
    
    public static void main(String[] args){  
        
        LocalDate localDate = LocalDate.of(2002, 01, 10);
        System.out.println(localDate);
        localDate = localDate.with(ChronoField.DAY_OF_YEAR, 35);
        System.out.println("New Date : "+localDate);
    }
}

Output:

2002-01-10 

New Date : 2002-02-04

Live Example:

Try with a live example, execute the code instantly with our powerful Online Java Compiler.

import java.time.LocalDate;
import java.time.temporal.ChronoField;
public class Main {
    
    public static void main(String[] args){  
        
        LocalDate localDate = LocalDate.of(2002, 01, 10);
        System.out.println(localDate);
        localDate = localDate.with(ChronoField.DAY_OF_MONTH, 05);
        System.out.println("New Date : "+localDate);
    }
}