Java Instant plusSeconds()

In this guide, you will learn about the Instant plusSeconds() method in Java programming and how to use it with an example.

1. Instant plusSeconds() Method Overview

Definition:

The plusSeconds() method of the Instant class in Java is used to add the specified number of seconds to this Instant. The method returns a new Instant object representing the resultant time.

Syntax:

public Instant plusSeconds(long secondsToAdd)

Parameters:

- secondsToAdd: The number of seconds to add, may be negative to subtract seconds.

Key Points:

- The plusSeconds() method can be used to modify the time represented by an Instant object by adding a certain number of seconds.

- If the number is negative, it will subtract the corresponding seconds from the Instant.

- The method is non-static and should be called on an instance of the Instant class.

- The method does not modify the original Instant object but rather returns a new object representing the modified time.

2. Instant plusSeconds() Method Example

import java.time.Instant;

public class InstantPlusSecondsExample {
    public static void main(String[] args) {
        // Creating the current Instant
        Instant instant = Instant.now();
        System.out.println("Current Instant: " + instant);

        // Adding 3600 seconds (1 hour) to the current Instant
        Instant newInstant = instant.plusSeconds(3600);
        System.out.println("New Instant after adding 3600 seconds: " + newInstant);

        // Subtracting 3600 seconds (1 hour) from the current Instant
        Instant subtractedInstant = instant.plusSeconds(-3600);
        System.out.println("Instant after subtracting 3600 seconds: " + subtractedInstant);
    }
}

Output:

Current Instant: 2023-09-20T10:00:00Z
New Instant after adding 3600 seconds: 2023-09-20T11:00:00Z
Instant after subtracting 3600 seconds: 2023-09-20T09:00:00Z

Explanation:

In this example, we created the current Instant and displayed it. We then used the plusSeconds() method to add 3600 seconds (1 hour) to the current Instant and displayed the new Instant. 

Similarly, we subtracted 3600 seconds (1 hour) from the current Instant by passing a negative parameter to the plusSeconds() method and displayed the resultant Instant.

Comments