The Unix timestamp is an integer value representing the number of seconds elapsed since the Unix Epoch on January 1st, 1970, at 00:00:00 UTC. In short, a Unix timestamp is the number of seconds between a specific date and the Unix Epoch.
There are multiple ways to compute a Unix timestamp in Java.
The simplest way to get a Unix atimestamp is using the
Instant class. The
Instant class is part of new date and time API and provides several methods to work with timestamps.
long unixTime = Instant.now().getEpochSecond(); System.out.println(unixTime); // 1665083712
getEpochSecond() method returns the seconds from the Unix epoch of
To convert a Unix timestamp back to an instance of
Instant, use the
long unixTime = 1665083712; Instant instant = Instant.ofEpochSecond(unixTime); System.out.println(instant); // 2022-10-06T19:15:12Z
Instant object represents an unique moment in the timeline using a universal timezone (UTC).
In Java 7 and below, you can use the
System.currentTimeMillis() method to get the current time in milliseconds.
Later, you can convert the milliseconds into seconds to get the Unix timestamp, as shown below:
long unixTime = System.currentTimeMillis() / 1000L; System.out.println(unixTime); // 1665083712
Finally, the last method to get the Unix timestamp in Java is using the legacy
Date date = new Date(); long unixTime = date.getTime() / 1000L; System.out.println(unixTime); // 1665083712
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