Java Instant Class | plusSeconds() Method with Example

Instant Class plusSeconds() method: Here, we are going to learn about the plusSeconds() method of Instant Class with its syntax and example.
Submitted by Preeti Jain, on May 26, 2020

Instant Class plusSeconds() method

  • plusSeconds() method is available in java.time package.
  • plusSeconds() method is used to add the given duration in seconds to this Instant and return the Instant.
  • plusSeconds() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • plusSeconds() method method may throw an exception at the time of performing addition.
    DateTimeException: This exception may throw when this Instant value reaches out of the min or max instant.

Syntax:

    public Instant plusSeconds(long sec_val);

Parameter(s):

  • long sec_val – represents the seconds value to add to this Instant.

Return value:

The return type of this method is Instant, it returns the Instant that holds the value added the given seconds to this Instant.

Example:

// Java program to demonstrate the example 
// of plusSeconds(long sec_val) method 
// of Instant

import java.time.*;

public class PlusSecondsOfInstant {
    public static void main(String args[]) {
        long seconds = 25;

        // Instantiates two Instant
        Instant ins1 = Instant.parse("2006-04-03T05:10:15.60Z");
        Instant ins2 = Instant.now();

        // Display ins1,ins2 and seconds
        System.out.println("Instant ins1 and ins2: ");
        System.out.println("ins1: " + ins1);
        System.out.println("ins2: " + ins2);
        System.out.println("seconds to add: " + seconds);

        System.out.println();

        // Here, this method adds the given duration
        // in seconds with this Instant ins1 
        // i.e. here we are adding the given 
        // 25 seconds with this ins1 

        Instant plus_sec = ins1.plusSeconds(seconds);

        // Display plus_sec
        System.out.println("ins1.plusSeconds(seconds): " + plus_sec);

        // Here, this method adds the given duration
        // in seconds with this Instant ins2 
        // i.e. here we are adding the given 
        // 25 seconds with this ins2 

        plus_sec = ins2.plusSeconds(seconds);

        // Display plus_sec
        System.out.println("ins2.plusSeconds(seconds): " + plus_sec);
    }
}

Output

Instant ins1 and ins2: 
ins1: 2006-04-03T05:10:15.600Z
ins2: 2020-05-27T00:25:09.640174Z
seconds to add: 25

ins1.plusSeconds(seconds): 2006-04-03T05:10:40.600Z
ins2.plusSeconds(seconds): 2020-05-27T00:25:34.640174Z



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.