Java Convert a Unix Timestamp to Date Time



Write program that converts a UNIX timestamp to a java.util.Date and java.time.LocalDateTime.


Check out Java 8 examples at Java 8 Examples
Checkout all Java programs at 50+ Java Programs 

Java Convert a Unix Timestamp to Date-Time

package net.sourcecodeexamples.java;

import java.text.ParseException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class Main {

    public static void main(String[] args) throws ParseException {

        long unixTimestamp = System.currentTimeMillis();

        Date date1 = new Date(unixTimestamp * 1000 L);
        Date date2 = new Date(TimeUnit.MILLISECONDS.convert(unixTimestamp, TimeUnit.SECONDS));

        System.out.println(unixTimestamp + " as date-time in default time zone is " + date1);
        System.out.println(unixTimestamp + " as date-time in default time zone is " + date2);

        // JDK 8        
        Instant instant = Instant.ofEpochSecond(unixTimestamp);
        Date date3 = Date.from(instant);
        LocalDateTime date4 = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Calcutta"));
        ZonedDateTime date5 = ZonedDateTime.ofInstant(instant, ZoneId.of("Asia/Calcutta"));

        System.out.println(unixTimestamp + " as date-time in default time zone is " + date3);
        System.out.println("\n" + unixTimestamp + " as date-time in Asia/Calcutta time zone is " + date4);
        System.out.println(unixTimestamp + " as date-time in Asia/Calcutta time zone is " +
            date5.format(DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss Z VV")));
        System.out.println("\n" + unixTimestamp + " as instant (UTC time) is " + instant);
    }

}

Output

1597138527667 as date-time in default time zone is Sat Apr 21 20:31:07 IST 52581
1597138527667 as date-time in default time zone is Sat Apr 21 20:31:07 IST 52581
1597138527667 as date-time in default time zone is Sat Apr 21 20:31:07 IST 52581

1597138527667 as date-time in Asia/Calcutta time zone is +52581-04-21T20:31:07
1597138527667 as date-time in Asia/Calcutta time zone is +52581-Apr-21 20:31:07 +0530 Asia/Calcutta

1597138527667 as instant (UTC time) is +52581-04-21T15:01:07Z

Comments