3

I have a timestamp I want to convert to a date. I tried this timestamp: 1336425840. This should be Mon, 07 May 2012 21:24:00 GMT, where GMT is the timezone the emulator should be set to. I tried this:

final Calendar c = Calendar.getInstance();
c.setTimeInMillis(1336425840*1000);
Date d = c.getTime();
Log.i("MyTag", "Hours: " + d.getHours());

The result is: Hours: 23.

So it seems like the returned date is computed according to GMT+2, which is the timezone set for my system. I expected g.hetHours() to return 21, since the emulator's timezone seems to be set to GMT.

Also, that timestamp results from reading the actual date in C using mktime, which seems to return the correct timestamp. But Java seems to refer to a different timezone. Am I doing anything wrong? Why isn't Mon, 07 May 2012 21:24:00 GMT returned?

Luca Carlon
  • 9,546
  • 13
  • 59
  • 91

2 Answers2

5

I'm pretty sure 1336425840*1000 will give you a value outside the regular range of int. In fact, if you would print the full date of the Calendar object, you'll see it displays Thu Jan 08 23:56:50 GMT 1970, which explains the 23 hours you see.

Change the multiplication to: (note the L at the end)

c.setTimeInMillis(1336425840 * 1000L);

// Edit: easy to confirm:

System.out.println((1336425840 * 1000L > Integer.MAX_VALUE));

:)

MH.
  • 45,303
  • 10
  • 103
  • 116
2

You should use a DateFormat object, and then set the time zone with setTimeZone().

Eric W.
  • 814
  • 1
  • 8
  • 18
  • Because by default it uses the current time zone of the computer you're on. You need to tell it to use GMT instead. – Eric W. May 10 '12 at 08:18