简体   繁体   中英

Java not converting epoch correctly

I'm trying to convert the following epoch time

1382364283

When plugging this into an online converter it gives me the correct results.

10/21/2013 15:00:28

But the following code

    Long sTime = someTime/1000;
    int test = sTime.intValue();  // Doing this to remove the decimal

    Date date = new Date(test);
    DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    String formatted = format.format(date);

    this.doorTime = formatted;

Returns

16/01/1970 17:59:24

I've tried several other ways to convert this, is there something I'm missing?

An epoch time is a count of seconds since epoch. You are dividing it by one thousand, gettings the number of thousands of seconds, that is, kiloseconds. But the parameter that Date takes is in milliseconds. Your code should be:

    long someTime = 1382364283;
    long sTime = someTime*1000;  // multiply by 1000, not divide

    Date date = new Date(sTime);
    DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    String formatted = format.format(date);

    System.out.println(formatted); // 21/10/2013 10:04:43

I don't get exactly your result, but I get the same results as online converters I tried.

The constructor Date(long time) takes a time in millis ! As you divide your someTime (which is probably in millis) by 1000, you get time in seconds instead of millis.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM