arnp
arnp

Reputation: 3208

How can I convert epoch time to date and time in Java?

I need to convert epoch timestamp to date and time. I have used the following code to convert but it converts to a wrong date, year and time.

String date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
                    .format(new java.util.Date (1319286637/1000));

Expected output was today’s date at some time, but the result I got was:

01/01/1970 05:51:59

Upvotes: 5

Views: 11173

Answers (2)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79620

In brief:

Instant.ofEpochSecond( 1_319_286_637L )

2011-10-22T12:30:37Z

Solution using java.time, the modern API:

import java.time.Instant;

public class Main {
    public static void main(String[] args) {
        Instant instant = Instant.ofEpochSecond(1319286637L);
        System.out.println(instant);
    }
}

Output:

2011-10-22T12:30:37Z

An Instant represents an instantaneous point on the timeline. The Z in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).

You can convert an Instant to other Date-Time types e.g.

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        Instant instant = Instant.ofEpochSecond(1319286637);
        ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Kolkata"));
        System.out.println(zdt);

        // A custom format
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss", Locale.ENGLISH);
        System.out.println(dtf.format(zdt));
    }
}

Output:

2011-10-22T18:00:37+05:30[Asia/Kolkata]
10/22/2011 18:00:37

Learn more about java.time, the modern Date-Time API* from Trail: Date Time.

Note: The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*. However, for any purpose, if you need to convert this object of Instant to an object of java.util.Date, you can do so as follows:

Date date = Date.from(instant);

* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Upvotes: 5

Mat
Mat

Reputation: 206909

The Date(long) constructor takes milliseconds. You should be multiplying by 1000, not dividing the epoch time you have.

Upvotes: 12

Related Questions