Instant minus() method in Java


An immutable copy of a instant where a time unit is subtracted from it can be obtained using the minus() method in the Instant class in Java. This method requires two parameters i.e. time to be subtracted from the instant and the unit in which it is to be subtracted. It also returns the immutable copy of the instant where the required time unit is subtracted.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.time.*;
import java.time.temporal.ChronoUnit;
public class Demo {
   public static void main(String[] args) {
      Instant i = Instant.now();
      System.out.println("The current instant is: " + i);
      Instant sub = i.minus(2, ChronoUnit.HOURS);
      System.out.println("The instant with 2 hours subtracted is: " + sub);
   }
}

Output

The current instant is: 2019-02-13T06:40:32.595Z
The instant with 2 hours subtracted is: 2019-02-13T04:40:32.595Z

Now let us understand the above program.

First the current instant is displayed. Then an immutable copy of the instant where 2 hours are subtracted is obtained using the minus() method and this is displayed. A code snippet that demonstrates this is as follows −

Instant i = Instant.now();
System.out.println("The current instant is: " + i);
Instant sub = i.minus(2, ChronoUnit.HOURS);
System.out.println("The instant with 2 hours subtracted is: " + sub);

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements