toSeconds() is a Duration which is used to get the number of seconds in the duration object. This method returns the total number of whole seconds in the duration.
The toSeconds method is defined in the Duration class. The Duration class is defined in the java.time package. To import the Duration class check the following import statement:
import java.time.Duration;
public long toSeconds()
The method has no parameters.
This method returns the whole seconds part of the length of the duration.
Lets have a look at the code showing the examples:
import java.util.*;import java.time.Duration;public class Main{public static void main(String[] args) {// Example 1Duration durationInMilliSeconds = Duration.ofMillis(10000);System.out.println("100 milliseconds in seconds - " + durationInMilliSeconds.toSeconds());// Example 2durationInMilliSeconds = Duration.ofMillis(-10000);System.out.println("100 milliseconds in seconds - " + durationInMilliSeconds.toSeconds());// Example 3Duration durationInMinutes = Duration.ofMinutes(10);System.out.println("10 minutes in seconds - " + durationInMinutes.toSeconds());}}
In the first example, we convert a duration of 10000 milliseconds to seconds. The toSeconds() method returns 10.
In the second example, we convert a duration of -10000 milliseconds to seconds. The sign of the duration is preserved in the output. The toSeconds() method returns -10.
In the first example, we convert a duration of 10 minutes to seconds. The toSeconds() method returns 600.
100 milliseconds in seconds - 10
100 milliseconds in seconds - -10
10 minutes in seconds - 600