Convert Timestamp to Local Date and Time

The YCM API returns response results with timestamp instead of detailed date and time, you can convert the timestamp to the local date and time as needed. This topic provides examples of converting timestamp to date in Java.

Convert timestamp using JDK8 or the later versions

 * JDK8 UNIX Time to  LocalDateTime
  public void testUnixTimeToLocalDateTime() {
        //unix time
        Long unixTime = 1636077838L;
        //millis time
        Long millisTime = unixTime * 1000;

        Instant instant = Instant.ofEpochMilli(millisTime);

        // system default time zone
        ZoneId defaultZoneId = ZoneId.systemDefault();
        //custom time zone
        ZoneId customZoneId = ZoneId.of("America/New_York");

        LocalDateTime defaultLocalDateTime = LocalDateTime.ofInstant(instant, defaultZoneId);
        LocalDateTime customLocalDateTime = LocalDateTime.ofInstant(instant, customZoneId);

        //String s = defaultLocalDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);

        System.out.println(defaultLocalDateTime); //2021-11-05T10:03:58
        System.out.println(customLocalDateTime); //2021-11-04T22:03:58

Convert timestamp using the former JDK versions

 *  UNIX Time to Date
public void testUnixTimeToDate() {

    Long unixTime = 1636077838L;

    // time formats
    String formats = "yyyy-MM-dd HH:mm:ss";
    Long timestamp = unixTime * 1000;
    String date = new SimpleDateFormat(formats, Locale.CHINA).format(new Date(timestamp)); // 2021-11-05 10:03:58