1

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?

user2229544
  • 477
  • 2
  • 10
  • 23
  • What is `sometime`? How is it defined and assigned its value? – PM 77-1 Oct 21 '13 at 15:09
  • 1
    What is the purpose of calling sTime.intValue()? A long can only store an integer.... By casting to integer, you potentially cause an overflow which messes up your result. And java time is in **milliseconds**, unless your input time is in microseconds, you should be multiplying by 1000 not dividing by it. – initramfs Oct 21 '13 at 15:10
  • Are you using `java.util.Date`? – PM 77-1 Oct 21 '13 at 15:13

2 Answers2

4

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.

Cyrille Ka
  • 15,328
  • 5
  • 38
  • 58
1

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.

Julien
  • 2,544
  • 1
  • 20
  • 25