Skip to main content

Java 8 API: java.time.Instant

Epoch time is the number of seconds since January 1st, 1970.

1 minute – 60 seconds

1 hour – 3600 seconds

1 day – 86400 seconds

Creating an Epoch Time

The easiest way to create epoch time is, using Systerm.currentTimeMillis()

This time format is not human readable, but it’s suitable to store in a database, business logic, etc. But problem is, calculation such as add or minus seconds, compare with other epoch times are difficult with this implementation.So that the Instant was introduced with Java 8.

Creating an Instant

Let see it’s usage

Convert to String

To a formatter an Instant a time-zone is required.


Convert to epoch format


Plus or Minus

The Instant class has several methods to plus or minus.

Some methods.

  • currentTime.plusMillis()
  • currentTime.plusNanos()
  • currentTime.plusSeconds()
  • currentTime.minusMillis()
  • currentTime.minusNanos()
  • currentTime.minusSeconds()

Plus or Minus with Temporal Units

Let say, we need to plus or minus few days or weeks. How do we deal with this? We can use TemporalUnits.


There no of Temperal Units such as SECONDS, MINUTES, HOURS, DAYS, WEEKS, MONTHS, YEARS, DECADES and so on. We can use with plus() and minus().

Java 8 API docs: ChronoUnit

What about adding 2 hours and 30 minutes?


For comparing 2 Instant, isBefore() or isAfter() can be used.


String to Instant

Use parse(), String or character sequence convert to an Instant.


Finally, Instant is immutable that means, it’s creating a new instance if you plus or minus.

Related Post

3058total visits,4visits today

Follow by Email