Java Convert Epoch Milliseconds to LocalDateTime

Tags: Java LocalDateTime Java 8

In this Java core tutorial we learn how to convert an epoch milliseconds value to a LocalDateTime object using date time API in Java programming language.

How to convert Epoch Milliseconds to LocalDateTime in Java

Epoch seconds is the number of milliseconds from 1970-01-01T00:00:00Z. In Java, with a given epoch seconds value we can use these steps to convert it to a LocalDateTime object.

  • Step 1: use the Instant.ofEpochMilli(long epochMilli) method to convert epoch milliseconds to Instant object.
  • Step 2: use Instant.atZone(ZoneId zone) to convert the Instant object from step 1 to a ZonedDateTime object in system default time zone.
  • Step 3: use the ZonedDateTime.toLocalDateTime() to convert the ZonedDateTime object at step 2 to LocalDateTime object.

ConvertEpochMillisecondsToLocalDateTimeExample1.java

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class ConvertEpochMillisecondsToLocalDateTimeExample1 {
    public static void main(String... args) {
        long epochMilliseconds = 1655227162222L;

        Instant instant = Instant.ofEpochMilli(epochMilliseconds);
        ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
        LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();

        System.out.println("Epoch Milliseconds: " + epochMilliseconds);
        System.out.println("LocalDateTime: " + localDateTime);
    }
}
The output as below.
Epoch Milliseconds: 1655227162222
LocalDateTime: 2022-06-15T00:19:22.222

Happy Coding 😊

Java Convert Epoch Days to LocalDateTime

Java Convert Epoch Seconds to LocalDate

Java Convert Epoch Milliseconds to LocalDate