In Java 8, we can use Instant.ofEpochMilli().atZone() to convert the epoch time in milliseconds back to LocalDate or LocalDateTime
Epoch time to LocalDate
LocalDate ld = Instant.ofEpochMilli(epoch).atZone(ZoneId.systemDefault()).toLocalDate();
Epoch time to LocalDateTime
LocalDateTime ldt = Instant.ofEpochMilli(epoch).atZone(ZoneId.systemDefault()).toLocalDateTime();
P.S Epoch time is the number of seconds that have elapsed since 0:00:00 UTC on 1 January 1970
1. Epoch Time -> LocalDate || LocalDateTime
Get the current epoch time in long value and convert it back to LocalDate or LocalDateTime.
Java8ConvertEpoch.java
package com.mkyong.java8;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
public class Java8ConvertEpoch {
public static void main(String[] args) {
long epoch = Instant.now().toEpochMilli();
System.out.println(epoch);
LocalDate ld = Instant.ofEpochMilli(epoch)
.atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(ld);
LocalDateTime ldt = Instant.ofEpochMilli(epoch)
.atZone(ZoneId.systemDefault()).toLocalDateTime();
System.out.println(ldt);
}
}
Output
1581420629955
2020-02-11
2020-02-11T19:30:29.955
References