How to Get Current Timestamp (Epoch) in Milliseconds in Java
There are several ways to get the current epoch timestamp in milliseconds in Java.
An epoch is the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC (i.e.
All of the options below return the same timestamp. The various options are a result of the evolution of the Java date API.
We can simply use currentTimeMillis() on the
long now = System.currentTimeMillis();
Instant class is also available to us in Java 8.
long now = Instant.now().toEpochMilli();
The use of the
Calendar class was replaced by java.time in Java 8, so it’s generally not recommended. However, it is still a valid option to obtain the current epoch timestamp.
Date date = new Date(); long now = date.getTime();
Calendar calendar = Calendar.getInstance(); long now = calendar.getTimeInMillis();