Java Instant minusSeconds()

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

1. Instant minusSeconds() Method Overview

Definition:

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

Syntax:

public Instant minusSeconds(long secondsToSubtract)

Parameters:

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

Key Points:

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

- If the number is negative, it effectively adds the corresponding seconds to 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 minusSeconds() Method Example

import java.time.Instant;

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

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

        // Adding 3600 seconds (1 hour) to the current Instant by subtracting negative seconds
        Instant addedInstant = instant.minusSeconds(-3600);
        System.out.println("Instant after adding 3600 seconds: " + addedInstant);
    }
}

Output:

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

Explanation:

In this example, we created the current Instant and displayed it. We then used the minusSeconds() method to subtract 3600 seconds (1 hour) from the current Instant and displayed the resultant Instant. Similarly, we added 3600 seconds (1 hour) to the current Instant by passing a negative parameter to the minusSeconds() method and displayed the resultant Instant.

Comments