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


Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap