views:

231

answers:

2

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?

A: 

If you do something with dates and times I would suggesst to replace the standard Java omplementation for Joda Time. It has much more sane way of dealing with time data.

Peter Tillemans
-1 No, not Joda time, and no details on how to do it in Joda time
Romain Hippeau
+2  A: 

You timezone string is formulated incorrectly. Try this,

String sign = secondsFromGMT > 0 ? "+" : "-";
secondsFromGMT = Math.abs(secondsFromGMT);      
int hours = secondsFromGMT/3600;
int mins = (secondsFromGMT%3600)/60;
String zone = String.format("GMT%s%02d:%02d", sign, hours, mins);          
TimeZone t = TimeZone.getTimeZone(zone);
ZZ Coder
Calculations for `hours` and `mins` should use `Math.abs(secondsFromGMT)`.
lins314159
That worked - thanks for the catch!
aloo