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?

1

2 Answers 2

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));

:)

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I just found it out myself. I noticed the 1970 :-D Thanks!
2

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

1 Comment

Because by default it uses the current time zone of the computer you're on. You need to tell it to use GMT instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.