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

In this article, we will learn how to subtract Second, Millisecond and Nanosecond fields from an Instant using different methods provided in the Java 1.8 version

Subtracting Second, Millisecond and Nanosecond from an Instant :

  • Subtracting Second, Millisecond and Nanosecond from an Instant is quite simple using different methods provided
  • Use below methods to subtract Second or Millisecond or Nanosecond fields from an Instant
    1. minusSeconds(secondsToSubtract) – Returns a copy of invoking Instant with the specified duration in seconds subtracted
    2. minusMillis(millisToSubtract) – Returns a copy of invoking Instant with the specified duration in milliseconds subtracted
    3. minusNanos(nanosToSubtract) – Returns a copy of invoking Instant with the specified duration in nanoseconds subtracted
  • In the below illustration, we are going to do below operations with default Instant,
    1. Subtract 125 Nanoseconds from an Instant using minusNanos() method
    2. Subtract 999 Milliseconds from an Instant using minusMillis() method
    3. Subtract 19 Seconds from an Instant using minusSeconds() method
  • Finally, print Instant after each operation to the console

SubtractFromInstant.java

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

import java.time.Instant;

public class SubtractFromInstant {

	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. subtract 125 Nanoseconds with current Instant
		Instant instant1 = instant.minusNanos(125);
		System.out.println("\n1. After subtracting 125 nanos to an Instant is  = "
				+ instant1);


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


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

Output:

Current Instant at UTC is :- 2022-08-22T05:06:12.652529900Z

1. After subtracting 125 nanos to an Instant is  = 2022-08-22T05:06:12.652529775Z
2. After subtracting 999 millis to an Instant is = 2022-08-22T05:06:11.653529900Z
3. After subtracting 19 seconds to an Instant is = 2022-08-22T05:05:53.652529900Z

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to check whether an Instant is Before another Instant ?
Java 8 – How to add Second, Millisecond and Nanosecond to an Instant ?