Java 8 Clock millis() Method with Examples
Last Updated :
17 Jun, 2021
Java Clock class is part of Date Time API, java.time.Clock, of Java. The Java Date Time API was added from Java version 8.
The millis() method of Clock class returns the current instant of the clock in milliseconds. A millisecond instant is measured from 1970-01-01T00:00Z (UTC) to the current time. This method does the same work as System.currentTimeMillis() method. If the creation of an object is unacceptable, then this method is used to allow the use of java.time.Clock in high-performance use cases.
Syntax:
public long millis()
Return Value: This method returns the current instant of the clock in milliseconds.
Exception: This method throws DateTimeException if the instant cannot be obtained from Clock.
Example::
Code:
Clock clock = Clock.systemDefaultZone();
long milliSeconds=clock.millis();
System.out.println(milliSeconds);
Output::
1534749202051
Explanation::
when millis() is called, then it returns a current instant
of Class Object in milliseconds.
Below programs illustrates millis() method of java.time.Clock class:
Program 1: Using millis() with Clock object created with systemDefaultZone
Java
import java.time.*;
public class millisMethodDemo {
public static void main(String[] args)
{
Clock clock = Clock.systemDefaultZone();
long milliseconds = clock.millis();
System.out.println( "Instant for class name "
+ clock + " in milliseconds is "
+ milliseconds);
}
}
|
Output
Instant for class name SystemClock[Etc/UTC] in milliseconds is 1623838188802
Program 2: Using millis with Clock object created with Zone “Europe/Paris”
Java
import java.time.*;
public class millisMethodDemo {
public static void main(String[] args)
{
ZoneId zoneId = ZoneId.of( "Europe/Paris" );
Clock clock = Clock.system(zoneId);
long milliseconds = clock.millis();
System.out.println( "Instant for clock class"
+ " in milliseconds is " + milliseconds);
}
}
|
Output
Instant for clock class in milliseconds is 1623837795533
Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#millis–
Share your thoughts in the comments
Please Login to comment...