Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Milliseconds to Date in GMT in Java

Tags:

java

date

android

I need to covert milliseconds to GMT date (in Android app), example:

1372916493000

When I convert it by this code:

Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
cal.setTimeInMillis(millis);
Date date = cal.getTime();

the result is 07:41 07/04/2013. The result is the same when I use just:

Date date = new Date(millis);

Unfortunately the result looks incorrect, it looks like my local time. I tried to convert the same number by this service and the result is 05:41 07/04/2013, which I believe is correct. So I have two hours difference. Anybody has any suggestion / tips what's wrong with my conversion?

like image 269
Michal Avatar asked Nov 30 '22 20:11

Michal


1 Answers

If result which looks incorrect means System.out.println(date) then it's no surprise, because Date.toString converts date into string representation in local timezone. To see result in GMT you can use this

SimpleDateFormat df = new SimpleDateFormat("hh:ss MM/dd/yyyy");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
String result = df.format(millis);
like image 65
Evgeniy Dorofeev Avatar answered Dec 04 '22 10:12

Evgeniy Dorofeev