How to Get Current Timestamp (Epoch) in Milliseconds in Java

Published Jul 16, 2022

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. 1970-01-01T00:00:00Z).

All of the options below return the same timestamp. The various options are a result of the evolution of the Java date API.

1. Using System.currentTimeMillis()

We can simply use currentTimeMillis() on the System class.

long now = System.currentTimeMillis();

2. Using Instant.now().toEpochMilli()

The Instant class is also available to us in Java 8.

long now = Instant.now().toEpochMilli();

3. Using Date or Calendar

The use of the Date and 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.

Using the Date class:

Date date = new Date();
long now = date.getTime();

Using the Calendar class:

Calendar calendar = Calendar.getInstance();
long now = calendar.getTimeInMillis();