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.favtuts.time;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;

public class EpochTimeConverter {
    
    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

1654416314232
2022-06-05
2022-06-05T15:05:14.232

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-basic/time

References

Leave a Reply

Your email address will not be published. Required fields are marked *