Studytonight is now part of the GUVI universe. Explore GUVI →
🤩 New Cool Developer Tools for you. Explore →
FREE JavaScript Video Series Start Learning →
Signup/Sign In
Tests
MCQs to test your knowledge.
Compilers
Compilers to execute code in browser.
Index
LAST UPDATED: NOVEMBER 27, 2020

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);
	}
}


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);
	}
}


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.

[フレーム]



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.

Learn to Code
Learn and practice coding side-by-side.
NEW
C language Course
115+ coding exercises
Javascript Course
85+ coding exercises

AltStyle によって変換されたページ (->オリジナル) /