java.time.Instant.with() Method Example



Description

The java.time.Instant.with(TemporalField field, long newValue) method returns a copy of this instant with the specified field set to a new value.

Declaration

Following is the declaration for java.time.Instant.with(TemporalField field, long newValue) method.

public Instant with(TemporalField field, long newValue)

Parameters

  • field − the field to set in the result, not null.

  • newValue − the new value of the field in the result.

Return Value

an Instant based on this with the specified field set, not null.

Exceptions

  • DateTimeException − if the field cannot be set.

  • UnsupportedTemporalTypeException - if the field is not supported.

  • ArithmeticException − if numeric overflow occurs.

Example

The following example shows the usage of java.time.Instant.with(TemporalField field, long newValue) method.

package com.tutorialspoint;

import java.time.Instant;
import java.time.temporal.ChronoField;

public class InstantDemo {
   public static void main(String[] args) {

      Instant instant = Instant.parse("2017-12-03T10:15:30.00Z");
      System.out.println(instant.with(ChronoField.NANO_OF_SECOND, 20));
   }
}

Let us compile and run the above program, this will produce the following result −

2017-12-03T10:15:30.000000020Z
Advertisements