Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top