Core Java

Java 8 Convert Instant to LocalDateTime Example

In this post, we feature a comprehensive Example on Java 8 Convert Instant to LocalDateTime. First we will learn about Java Instance and LocalDateTime class and then how to convert an Instant object to LocalDateTime.

1. Introduction

First we will have a look at the Instant class.

java.time.Instant

This class models a single instantaneous point on the time-line. This might be used to record event time-stamps in the application.

public final class Instant
extends Object
implements Temporal, TemporalAdjuster, Comparable, Serializable

 
The range of an instant requires the storage of a number larger than a long. To achieve this, the class stores a long representing epoch-seconds and an int representing nanoseconds-of-second, which will always be between 0 and 999,999,999. The epoch-seconds are measured from the standard Java epoch of 1970-01-01T00:00:00Z where instants after the epoch have positive values, and earlier instants have negative values. For both epoch-second and nanosecond parts, a larger value is always later on the time-line than the smaller value.

Time-scale

The length of the solar day is the standard way that humans measure time. This has traditionally been subdivided into 24 hours of 60 minutes of 60 seconds, forming a 86400 second day. Modern timekeeping is based on atomic clocks which precisely define an SI second relative to the transitions of a Caesium atom. The length of an SI second was defined to be very close to the 86400th fraction of a day.

Unfortunately, as the Earth rotates the length of the day varies. In addition, over time the average length of the day is getting longer as the Earth slows. As a result, the length of a solar day in 2012 is slightly longer than 86400 SI seconds. The actual length of any given day and the amount by which the Earth is slowing are not predictable and can only be determined by measurement. The UT1 time-scale captures the accurate length of day, but is only available some time after the day has completed.

The UTC time-scale is a standard approach to bundle up all the additional fractions of a second from UT1 into whole seconds, known as leap-seconds. A leap-second may be added or removed depending on the Earth’s rotational changes. As such, UTC permits a day to have 86399 SI seconds or 86401 SI seconds where necessary in order to keep the day aligned with the Sun.

The modern UTC time-scale was introduced in 1972, introducing the concept of whole leap-seconds. Between 1958 and 1972, the definition of UTC was complex, with minor sub-second leaps and alterations to the length of the notional second. As of 2012, discussions are underway to change the definition of UTC again, with the potential to remove leap seconds or introduce other changes.

Given the complexity of accurate timekeeping described above, this Java API defines its own time-scale, the Java Time-Scale. The Java Time-Scale divides each calendar day into exactly 86400 subdivisions, known as seconds. These seconds may differ from the SI second. It closely matches the de facto international civil time scale, the definition of which changes from time to time.

The Java Time-Scale has slightly different definitions for different segments of the time-line, each based on the consensus international time scale that is used as the basis for civil time. Whenever the internationally-agreed time scale is modified or replaced, a new segment of the Java Time-Scale must be defined for it. Each segment must meet these requirements:

  • the Java Time-Scale shall closely match the underlying international civil time scale;
  • the Java Time-Scale shall exactly match the international civil time scale at noon each day;
  • the Java Time-Scale shall have a precisely-defined relationship to the international civil time scale.

There are currently, as of 2013, two segments in the Java time-scale.

For the segment from 1972-11-03 until further notice, the consensus international time scale is UTC (with leap seconds). In this segment, the Java Time-Scale is identical to UTC-SLS. This is identical to UTC on days that do not have a leap second. On days that do have a leap second, the leap second is spread equally over the last 1000 seconds of the day, maintaining the appearance of exactly 86400 seconds per day.

For the segment prior to 1972-11-03, extending back arbitrarily far, the consensus international time scale is defined to be UT1, applied proleptically, which is equivalent to the (mean) solar time on the prime meridian (Greenwich). In this segment, the Java Time-Scale is identical to the consensus international time scale. The exact boundary between the two segments is the instant where UT1 = UTC between 1972-11-03T00:00 and 1972-11-04T12:00.

The Java time-scale is used for all date-time classes. This includes Instant, LocalDate, LocalTime, OffsetDateTime, ZonedDateTime and Duration.

This is a value-based class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of Instant may have unpredictable results and should be avoided. The equals method should be used for comparisons.

java.time.LocalDateTime

public final class LocalDateTime
extends Object
implements Temporal, TemporalAdjuster, ChronoLocalDateTime, Serializable

LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value “2nd October 2007 at 13:45.30.123456789” can be stored in a LocalDateTime.

This class does not store or represent a time-zone. Instead, it is a description of the date, as used for birthdays, combined with the local time as seen on a wall clock. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.

The ISO-8601 calendar system is the modern civil calendar system used today in most of the world. It is equivalent to the proleptic Gregorian calendar system, in which today’s rules for leap years are applied for all time. For most applications written today, the ISO-8601 rules are entirely suitable. However, any application that makes use of historical dates, and requires them to be accurate will find the ISO-8601 approach unsuitable.

This is a value-based class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of LocalDateTime may have unpredictable results and should be avoided. The equals method should be used for comparisons.

2. Conversion

In this section we will see how to convert an Instant object to LocalDateTime. We will create a very simple java class to achieve this.

Let say we want to convert the current time represented in Instant to the LocalDateTime. First we will create an Instant object:

Instant instant = Instant.now();

Now we will use the ofInstant() method of LocalDateTime class to convert the current time represented as Instant object to LocalDateTime object

LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);

The ofInstant() method creates a local date-time based on the specified instant. First, the offset from UTC/Greenwich is obtained using the zone ID and instant, which is simple as there is only one valid offset for each instant. Then, the instant and offset are used to calculate the local date-time.
Below is the full source code of the class:

InstantToLocalDateTime.java

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

public class InstantToLocalDateTime {

    public static void main(String[] args) {
        Instant instant = Instant.now();
        System.out.println("Instant: " + instant);

        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
        System.out.println("LocalDateTime: " + localDateTime);
    }

}

You will see the a similar output as below depending on when you run this class:

Instant: 2018-09-06T09:11:35.567Z
LocalDateTime: 2018-09-06T09:11:35.567

3. Java 8 Convert Instant to LocalDateTime – Conclusion

In this article we learned about the Instant and LocalDateTime class for java and also saw how to convert the Instant object to LocalDateTime. There are other classes which deals with the date and time but their functions are different. Depending on your requirement you need to choose the correct class which can solve the problem for you.

4. Download the Source Code

That was Java 8 Convert Instant to LocalDateTime Example.

Download
You can download the full source code of this example here: Instant to LocalDateTime

Mohammad Meraj Zia

Senior Java Developer
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button