How to convert Milliseconds to Date in Java 8 and Above

In order to convert milliseconds to a date in Java 8 and above, we can use the java.time.Instant from the new Java Date & Time API.


Example:

package org.code2care.examples;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Example: Convert Milliseconds
 * to LocalDate in Date
 *
 */
public class Example {

    public static void main(String... args) {

        long milliseconds = 161272138234L;
        String dateFormat = "yyyy-MM-dd HH:mm:ss";

        Instant instant = Instant.ofEpochMilli(milliseconds);

        ZoneId zoneId = ZoneId.of("UTC");
        ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, zoneId);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
        String formattedDate = zonedDateTime.format(formatter);

        System.out.println("Milliseconds to date: " + formattedDate);
    }
}


Output:

Milliseconds to date: 1975-02-10 13:48:58


Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!