converting a UTC time to a local time zone in Java
Posted
by aloo
on Stack Overflow
See other posts from Stack Overflow
or by aloo
Published on 2010-06-09T21:20:12Z
Indexed on
2010/06/09
23:52 UTC
Read the original article
Hit count: 182
I know this subject has been beaten to death but after searching for a few hours to this problem I had to ask.
My Problem: do calculations on dates on a server based on the current time zone of a client app (iphone). The client app tells the server, in seconds, how far away its time zone is away from GMT. I would like to then use this information to do computation on dates in the server. The dates on the server are all stored as UTC time. So I would like to get the HOUR of a UTC Date object after it has been converted to this local time zone.
My current attempt:
int hours = (int) Math.floor(secondsFromGMT / (60.0 * 60.0));
int mins = (int) Math.floor((secondsFromGMT - (hours * 60.0 * 60.0)) / 60.0);
String sign = hours > 0 ? "+" : "-";
Calendar now = Calendar.getInstance();
TimeZone t = TimeZone.getTimeZone("GMT" + sign + hours + ":" + mins);
now.setTimeZone(t);
now.setTime(someDateTimeObject);
int hourOfDay = now.get(Calendar.HOUR_OF_DAY);
The variables hour and mins represent the hour and mins the local time zone is away from GMT. After debugging this code - the variables hour, mins and sign are correct.
The problem is hourOfDay does not return the correct hour - it is returning the hour as of UTC time and not local time. Ideas?
© Stack Overflow or respective owner