Java Duration Class | plusSeconds() Method with Example

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

Duration Class plusSeconds() method

  • plusSeconds() method is available in java.time package.
  • plusSeconds() method is used to add the given duration in seconds to this Duration and return the Duration.
  • 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 may throw an exception at the time of performing addition.
    ArithmeticException: This exception may throw when the calculated results exceed the length of this Duration.

Syntax:

    public Duration plusSeconds(long sec_val);

Parameter(s):

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

Return value:

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

Example:

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

import java.time.*;

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

        // Instantiates two Duration objects
        Duration du1 = Duration.ofSeconds(40);
        Duration du2 = Duration.ofMinutes(1);

        // Display du1, du2 
        System.out.println("du1: " + du1);
        System.out.println("du2: " + du2);
        System.out.println("seconds to add: " + seconds);

        System.out.println();

        // adds the given duration in seconds with 
        // this Duration du1 and returns the Duration 
        // i.e. here we are adding the given 10 seconds
        // with this du1 that holds the value of 
        // 40 seconds i.e. 40S + 10S = 50S
        Duration plus_val = du1.plusSeconds(seconds);

        // Display plus_val
        System.out.println("du1.plusSeconds(seconds): " + plus_val);

        // adds the given duration in seconds with 
        // this Duration du2 and returns the Duration 
        // i.e. here we are adding the given 10 seconds
        // with this du2 that holds the value of 
        // 1M i.e. 1M + 10S = 1M 10S
        plus_val = du2.plusSeconds(seconds);

        // Display plus_val
        System.out.println("du2.plusSeconds(seconds): " + plus_val);
    }
}

Output

du1: PT40S
du2: PT1M
seconds to add: 10

du1.plusSeconds(seconds): PT50S
du2.plusSeconds(seconds): PT1M10S


Comments and Discussions!

Load comments ↻





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