Instant plus() method in Java


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

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 add = i.plus(2, ChronoUnit.HOURS);
      System.out.println("The instant with 2 hours added is: " + add);
   }
}

Output

The current instant is: 2019-02-13T06:33:27.414Z
The instant with 2 hours added is: 2019-02-13T08:33:27.414Z

Now let us understand the above program.

First the current instant is displayed. Then an immutable copy of the instant where 2 hours are added is obtained using the plus() 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 add = i.plus(2, ChronoUnit.HOURS);
System.out.println("The instant with 2 hours added is: " + add);

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements