ChronoLocalDate with(TemporalField, long) Method in Java with Examples
with(TemporalField field, long newValue) method of the ChronoLocalDate interface used to set the specified field of ChronoLocalDate to a new value and returns the copy of new date-time.This method can be used to change any supported field, such as the year, month or day-of-month. An exception is thrown If setting the new value is not possible due to the field is not supported or for some other reason.
In some cases, changing the specified field can cause the resulting date-time to become invalid, such as changing the month from 31st January to February would make the day-of-month invalid. In cases like this, the field is responsible for resolving the date. Typically it will choose the previous valid date, which would be the last valid day of February in this example. This instance of ChronoLocalDate is immutable and unaffected by this method call.
Syntax:
public ChronoLocalDate with(TemporalField field, long newValue)
Parameters: This method accepts field which is the field to set in the result and newValue which the new value of the field in the result as parameters.
Return value: This method returns a ChronoLocalDate based on this with the specified field set.
Exception: This method throws following Exceptions:
- DateTimeException – if the adjustment cannot be made.
- UnsupportedTemporalTypeException – if the field is not supported.
- ArithmeticException – if numeric overflow occurs.
Below programs illustrate the with() method:
Program 1:
import java.time.*;
import java.time.temporal.*;
import java.time.chrono.*;
public class GFG {
public static void main(String[] args)
{
ChronoLocalDate local
= LocalDate.parse(
"2018-12-06" );
System.out.println( "ChronoLocalDate before"
+ " applying method: "
+ local);
ChronoLocalDate updatedlocal
= local.with(
ChronoField.DAY_OF_MONTH, 30 );
System.out.println( "ChronoLocalDate after"
+ " applying method: "
+ updatedlocal);
}
}
|
Output:
ChronoLocalDate before applying method: 2018-12-06
ChronoLocalDate after applying method: 2018-12-30
References: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoLocalDate.html#with-java.time.temporal.TemporalField-long-
Last Updated :
29 Apr, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...