# How to get the Unix timestamp in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Dec 23, 2019, updated Oct 6, 2022. Topics: Java.
Canonical URL: https://attacomsian.com/blog/java-get-unix-timestamp

> A brief article to learn how to get the Unix timestamp in Java.

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](https://attacomsian.com/blog/java-new-date-time-api) and provides several methods to work with timestamps.

```java
long unixTime = Instant.now().getEpochSecond();

System.out.println(unixTime);
// 1665083712
```

The `getEpochSecond()` method returns the seconds from the Unix epoch of `1970-01-01T00:00:00Z`.

To convert a Unix timestamp back to an instance of `Instant`, use the `Instant.ofEpochSecond()` method:

```java
long unixTime = 1665083712;
Instant instant = Instant.ofEpochSecond(unixTime);

System.out.println(instant);
// 2022-10-06T19:15:12Z
```

An `Instant` object represents an [unique moment](https://attacomsian.com/blog/java-get-current-timestamp) 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:

```java
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` class:

```java
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](https://attacomsian.com/blog/java-new-date-time-api)
* [How to get current date and time in Java](https://attacomsian.com/blog/java-get-current-date-time)
* [How to convert a string to date in Java](https://attacomsian.com/blog/java-convert-string-to-date)
