The UNIX timestamp (also known as POSIX time or EPOCH time) is a way to compute time as a running total of seconds that have elapsed since Thursday, 1 January 1970, 00:00:00 Coordinated Universal Time (UTC), minus the number of leap seconds that have elapsed since then.
Unix time is widely used in Unix-like operating systems file formats. There are multiple ways to compute Unix timestamp in Java.
In Java 8 and higher, you can use the
Instant class from new date and time API to get the UNIX timestamp as shown below:
long unixTime = Instant.now().getEpochSecond(); // 1577094336
To convert a Unix timestamp back to an instance of
Instant, you can do the following:
long unixTime = 1577094336; Instant instant = Instant.ofEpochSecond(unixTime); // 2019-12-23T09:45:36Z
In Java 7 and below, you can use the
System.currentTimeMillis() method to get the current time in milliseconds. Then you can convert the milliseconds into seconds to get the Unix timestamp as shown below:
long unixTime = System.currentTimeMillis() / 1000L; // 1577094529
Finally, the last method to get the Unix timestamp in Java is by using the legacy
Date date = new Date(); long unixTime = date.getTime() / 1000L; // 1577094646
You may be interested in reading the following Java date and time tutorials:
- Introduction to Java 8 Date and Time API
- How to get current date and time in Java
- How to convert a string to date in Java
Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: email@example.com.