Home »
Java »
Java Reference »
Java Duration Class
Java Duration Class | toMillis() Method with Example
Duration Class toMillis() method: Here, we are going to learn about the toMillis() method of Duration Class with its syntax and example.
Submitted by Preeti Jain, on May 17, 2020
Duration Class toMillis() method
- toMillis() method is available in java.time package.
- toMillis() method is used to convert this Duration into the number of milliseconds.
- toMillis() 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.
- toMillis() method does not throw an exception at the time of converting this Duration to milliseconds.
Syntax:
public long toMillis();
Parameter(s):
Return value:
The return type of this method is long, it returns the number of milliseconds exists in this Duration.
Example:
// Java program to demonstrate the example
// of long toMillis() method of Duration
import java.time.*;
public class ToMillisOfDuration {
public static void main(String args[]) {
// Instantiates two Duration objects
Duration du1 = Duration.ofMinutes(1);
Duration du2 = Duration.parse("P0DT0H0M1S");
// Display du1 and du2
System.out.println("du1: " + du1);
System.out.println("du2: " + du2);
// represents this Duration du1 of minutes into
// number of milliseconds
long to_millis = du1.toMillis();
// Display to_millis
System.out.println("du1.toMillis(): " + to_millis);
// represents this Duration du2 of seconds into
// number of milliseconds
to_millis = du2.toMillis();
// Display to_millis
System.out.println("du2.toMillis(): " + to_millis);
}
}
Output
du1: PT1M
du2: PT1S
du1.toMillis(): 60000
du2.toMillis(): 1000