Java Clock millis()
May 20, 2019
Java Clock.millis
gets the current millisecond instant of the clock. millis
method returns the millisecond-based instant measured from 1970-01-01T00:00Z (UTC). millis
is equivalent to the definition of System.currentTimeMillis()
. To get an instant on the time-line, we should use Instant
instead of millis
. According to Java, we should use millis
only in high performance use-cases where the creation of an object would be unacceptable.
Find the declaration of
Clock.millis
from Java doc.
public long millis()
Now find the examples.
Example-1: We are instantiating clock with default zone and then calling
millis
on this clock.
MillisDefaultZone.java
package com.concretepage; import java.time.Clock; public class MillisDefaultZone { public static void main(String[] args) { Clock clock = Clock.systemDefaultZone(); long millis = clock.millis(); System.out.println(millis); } }
1558345581477
millis
on this clock.
MillisSpecifiedZone.java
package com.concretepage; import java.time.Clock; import java.time.ZoneId; public class MillisSpecifiedZone { public static void main(String[] args) { ZoneId zone = ZoneId.of("Asia/Calcutta"); Clock clock = Clock.system(zone); long millis = clock.millis(); System.out.println(millis); } }
1558345649093
Clock.systemUTC
. It returns the clock that gives current instant using UTC time-zone. Now we are calling millis
on this clock.
MillisSystemUTC.java
package com.concretepage; import java.time.Clock; public class MillisSystemUTC { public static void main(String[] args) { Clock clock = Clock.systemUTC(); long millis = clock.millis(); System.out.println(millis); } }
1558345693056
Clock.fixed
. It returns a fixed clock that always gives the same instant. Now we are calling millis
on this clock.
MillisFixed.java
package com.concretepage; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; public class MillisFixed { public static void main(String[] args) { Instant instant = Instant.parse("2019-05-18T15:34:42.00Z"); ZoneId zoneId = ZoneId.of("Asia/Calcutta"); Clock clock = Clock.fixed(instant, zoneId); for (int i = 1; i <= 3; i++) { System.out.println("-----" + i + "-----"); System.out.println(clock.millis()); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
-----1----- 1558193682000 -----2----- 1558193682000 -----3----- 1558193682000
References
Java Doc: Class ClockJava Clock