This post will discuss how to get the number of milliseconds/seconds that have elapsed since the Unix epoch. The Unix epoch is 00:00:00 UTC on 1 January 1970.

1. Using System.currentTimeMillis() method

The System.currentTimeMillis() method returns the difference between the current time and midnight, January 1, 1970, UTC in milliseconds.

Download  Run Code

Output (will vary):

1640353547371

 
The System.currentTimeMillis() method returns the current time in milliseconds. You can easily convert the time to seconds by dividing the output by 1000.

Download  Run Code

Output (will vary):

1640353563

2. Using Instant.toEpochMilli() method

The Instant class represents a point on the timeline. To obtain the current instant using the system clock, you can use the Instant.now() method. To convert this instant to the number of milliseconds from the epoch, use the toEpochMilli() method.

Download  Run Code

Output (will vary):

1640353580825

 
Alternatively, you can convert this instant to the number of seconds elapsed since the Unix epoch with the getEpochSecond() method.

Download  Run Code

Output (will vary):

1640353593

That’s all about getting milliseconds elapsed since the epoch in Java.