Trusted answers to developer questions

What is Duration.toSeconds() in Java?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

Introduction

toSeconds() is a staticthe methods in Java that can be called without creating an object of the class. method of the 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;

Syntax


public long toSeconds()

Parameters

The method has no parameters.

Return value

This method returns the whole seconds part of the length of the duration.

Code

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 1
Duration durationInMilliSeconds = Duration.ofMillis(10000);
System.out.println("100 milliseconds in seconds - " + durationInMilliSeconds.toSeconds());
// Example 2
durationInMilliSeconds = Duration.ofMillis(-10000);
System.out.println("100 milliseconds in seconds - " + durationInMilliSeconds.toSeconds());
// Example 3
Duration durationInMinutes = Duration.ofMinutes(10);
System.out.println("10 minutes in seconds - " + durationInMinutes.toSeconds());
}
}

Example 1

In the first example, we convert a duration of 10000 milliseconds to seconds. The toSeconds() method returns 10.

Example 2

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.

Example 3

In the first example, we convert a duration of 10 minutes to seconds. The toSeconds() method returns 600.

Output


100 milliseconds in seconds - 10
100 milliseconds in seconds - -10
10 minutes in seconds - 600

RELATED TAGS

java
toseconds
duration
static
Did you find this helpful?