Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
tomillis
duration
time

What is Duration.toMillis() in Java?

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

toMillis() is an instance method of the Duration class which is used to convert the duration time length to milliseconds. If the duration value is too large to fit in the long datatype, then an exception is thrown.

The toMillis() 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 toMillis()

Parameters

The method has no parameters.

Return value

This method returns the total length of the duration in milliseconds.

Code

In the below code, Duration class objects of different time units are converted to milliseconds.

Lets have a look at the code:

import java.time.Duration;
public class Main{
public static void main(String[] args) {
//Example 1
Duration durationInSeconds = Duration.ofSeconds(100);
System.out.println("100 seconds in milliseconds - " + durationInSeconds.toMillis());
//Example 2
Duration durationInMinutes = Duration.ofMinutes(10);
System.out.println("10 minutes in milliseconds - " + durationInMinutes.toMillis());
}
}

Example

Let’s look at the code:

import java.time.Duration;
public class Main{
public static void main(String[] args) {
//Example 3 to check exception
Duration durationInMinutes = Duration.ofMinutes(1000000000000000);
System.out.println("1000000000000000 minutes in milliseconds - " + durationInMinutes.toMillis());
}
}

RELATED TAGS

java
communitycreator
tomillis
duration
time

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring