Duration withSeconds(long) method in Java with Examples

The withSeconds(long) method of Duration Class in java.time package is used to get an immutable copy of this duration with the specified amount of seconds passed as the parameter.

Syntax:

public Duration withSeconds(long amountOfSeconds)

Parameters: This method accepts a parameter amountOfSeconds which is the amount of seconds.



Return Value: This method returns a Duration of the seconds passed as the parameter.

Below examples illustrate the Duration.withSeconds() method:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to illustrate withSeconds() method
  
import java.time.Duration;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the amount of seconds
        long amountOfSeconds = 300;
  
        // Duration using parse() method
        Duration duration
            = Duration.parse("P2DT3H4M");
  
        // Get the duration in seconds
        // using withSeconds() method
        System.out.println(duration
                               .withSeconds(amountOfSeconds));
    }
}

chevron_right


Output:

PT5M

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to illustrate withSeconds() method
  
import java.time.Duration;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the amount of seconds
        long amountOfSeconds = 3000;
  
        // Duration using ofHours() method
        Duration duration
            = Duration.ofHours(5);
  
        // Get the duration in seconds
        // using withSeconds() method
        System.out.println(duration
                               .withSeconds(amountOfSeconds));
    }
}

chevron_right


Output:

PT50M

Reference: https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#withSeconds-long-



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.