Java Data Type How to - Convert time in millis since epoch to "mm/dd/yy"








Question

We would like to know how to convert time in millis since epoch to "mm/dd/yy".

Answer

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
/*from   w  w  w.j a  va 2  s . c o m*/
public class Main {

    public static void main(String[] args) {
        String strDate = "2015-09-12 23:59:59";
        String pattern = "yyyy-MM-dd HH:mm:ss";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        ZoneId zone = ZoneId.of("America/Los_Angeles");

        long milli = getMillis(strDate, formatter, zone);                       
        System.out.println(milli);
    }

    private static long getMillis(String strDate, DateTimeFormatter formatter, ZoneId zone) {
        LocalDateTime localDateTime = LocalDateTime.parse(strDate, formatter);
        ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zone);
        Instant instant = zonedDateTime.toInstant();
        long milli = instant.toEpochMilli();
        return milli;
    }


}

The code above generates the following result.