Get milliseconds elapsed since epoch in Java
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.
|
1 2 3 4 5 6 |
public class Main { public static void main(String[] args) { long ms = System.currentTimeMillis(); System.out.println(ms); } } |
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.
|
1 2 3 4 5 6 |
public class Main { public static void main(String[] args) { long timestamp = System.currentTimeMillis() / 1000; System.out.println(timestamp); } } |
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.
|
1 2 3 4 5 6 7 8 |
import java.time.Instant; public class Main { public static void main(String[] args) { long ms = Instant.now().toEpochMilli(); System.out.println(ms); } } |
Output (will vary):
1640353580825
Alternatively, you can convert this instant to the number of seconds elapsed since the Unix epoch with the getEpochSecond() method.
|
1 2 3 4 5 6 7 8 |
import java.time.Instant; public class Main { public static void main(String[] args) { long timestamp = Instant.now().getEpochSecond(); System.out.println(timestamp); } } |
Output (will vary):
1640353593
That’s all about getting milliseconds elapsed since the epoch in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)