Java Data Type How to - Convert long type timestamp to LocalDate and LocalDateTime








Question

We would like to know how to convert long type timestamp to LocalDate and LocalDateTime.

Answer

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.TimeZone;
//ww  w . j  a  v a2 s . c  om
public class Main {

  public static void main(String[] args) {
    System.out.println(getDateTimeFromTimestamp(System.currentTimeMillis()));
    System.out.println(getDateFromTimestamp(System.currentTimeMillis()));
  }

  public static LocalDateTime getDateTimeFromTimestamp(long timestamp) {
    if (timestamp == 0)
      return null;
    return LocalDateTime.ofInstant(Instant.ofEpochSecond(timestamp), TimeZone
        .getDefault().toZoneId());
  }

  public static LocalDate getDateFromTimestamp(long timestamp) {
    LocalDateTime date = getDateTimeFromTimestamp(timestamp);
    return date == null ? null : date.toLocalDate();
  }
}

The code above generates the following result.