Instant Class In Java 8 Date Time API

 An Instant is a point on the timeline. This timeline maintain precision in nanosecond. We have a new concept of Date in Java 8 which is an Instant of time. LocalDate and ZonedDateTime classes introduced newly in Java 8 Date and Time API, this classed provide a human view on time. Sometimes we need to work with machine based time perspective like java.sql.Timestamp. For this we can use the Instant class which represents timestamps. An Instant counts the time beginning from the first second of January 1, 1970 (1970-01-01 00:00:00) also called the EPOCH. Instant values can be negative if they occured before the epoch. They follow ISO 8601 the standard for representing date and time.

 

July 4th           ->                July 17th           ->                 July 21th                ->                 July 29th

————————————————–Timeline—————————————————————>

Some useful facts about Instant Class

Instant 0  is the January 1st , 1970 at midnight GMT

Instant.MIN()  is a 1 billion year ago.

Instant.MAX () is  Dec 31 of the year 1,000,000,000

Instant.NOW()  is the current instant

 

1 billion years ago           ->                Instant.now()                 ->              1 billion years ahead

————————————————–Timeline—————————————————————>

 

Note: An Instant object is immutable. So unlike Date class of java.util.Date package, which is mutable, we no need to use defensive pattern.

Using new Instant Class

There are many cases where a date is not an Instant.

1) Sardar Patel was born October 31st,1875: It can not be covered by Instant Class concept. Why because it is date in the past and it doesn’t have nano second precision off course, it’s just a day precision.

2) Let us meet at 1PM and have lunch together: This is also not an Instant either. It’s just an hour in a day. And we are supposing in conversation what day we are talking about.

So we need some other concept for those dates. To solve this issue Java 8 introduced LocalDate class.

Reference:

Instant Class Java 8 Doc

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *