Java 8 – How to add Second, Millisecond and Nanosecond to an Instant ?

In this article, we will learn how to add Seconds, Milliseconds and Nanoseconds fields to an Instant using different methods provided in the Java 1.8 version

Adding Second, Millisecond and Nanosecond to an Instant :

  • Adding Second, Millisecond and Nanosecond to an Instant is quite simple using different methods provided
  • Use below methods to add Second or Millisecond or Nanosecond fields to an Instant
    1. plusSeconds(secondsToAdd) – Returns a copy of invoking Instant with the specified duration in seconds added
    2. plusMillis(millisToAdd) – Returns a copy of invoking Instant with the specified duration in milliseconds added
    3. plusNanos(nanosToAdd) – Returns a copy of invoking Instant with the specified duration in nanoseconds added
  • In the below illustration, we are going to do below operations with default Instant,
    1. Add 125 Nanoseconds to an Instant using plusNanos() method
    2. Add 999 Milliseconds to an Instant using plusMillis() method
    3. Add 19 Seconds to an Instant using plusSeconds() method
  • Finally, print Instant after each operation to the console

AddToInstant.java

package in.bench.resources.java8.instant.examples;

import java.time.Instant;

public class AddToInstant {

	public static void main(String[] args) {

		// get current Date/time or Instant at UTC
		Instant instant = Instant.now();
		System.out.println("Current Instant at UTC is :- "
				+ instant);


		// 1. add 125 Nanoseconds with current Instant
		Instant instant1 = instant.plusNanos(125);
		System.out.println("\n1. After adding 125 nanos to an Instant is  = "
				+ instant1);


		// 2. add 999 Milliseconds with current Instant
		Instant instant2 = instant.plusMillis(999);
		System.out.println("2. After adding 999 millis to an Instant is = "
				+ instant2);


		// 3. add 19 Seconds with current Instant
		Instant instant3 = instant.plusSeconds(19);
		System.out.print("3. After adding 19 seconds to an Instant is = "
				+ instant3);
	}
}

Output:

Current Instant at UTC is :- 2022-08-22T04:59:38.364241100Z

1. After adding 125 nanos to an Instant is  = 2022-08-22T04:59:38.364241225Z
2. After adding 999 millis to an Instant is = 2022-08-22T04:59:39.363241100Z
3. After adding 19 seconds to an Instant is = 2022-08-22T04:59:57.364241100Z

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to subtract Second, Millisecond and Nanosecond from an Instant ?
Java 8 – How to convert Instant to XMLGregorianCalendar and vice-versa ?