I have a Times开发者_如何学Gotamp value that comes from my application. The user can be in any given local TimeZone.
This date is used for a WebService and the system irrespective of what timezone user is in always picks up the server timezone(placed in US), I have a need to convert the parameter from system's to user's. I tried this approach:
/**
* Adapt calendar to client time zone.
* @param calendar - adapting calendar
* @param timeZone - client time zone
* @return adapt calendar to client time zone
*/
public static Calendar convertCalendar(final Calendar calendar,
final TimeZone timeZone){
Calendar ret = new GregorianCalendar(timeZone);
ret.setTimeInMillis(calendar.getTimeInMillis() +
timeZone.getOffset(calendar.getTimeInMillis()) -
TimeZone.getDefault().getOffset(calendar.getTimeInMillis()));
ret.getTime();
return ret;
}
There is a syntax error shown on my computer which says that the declaration "public static Calendar convertCalendar(Calendar calendar,TimeZone timeone)" has syntactic problem.
I am using JDK 1.3. I am not sure as to what am I missing.
Can anyone please improve my understanding on this concept?
In fact, to simply get a Calendar object which has the same raw time value but is in a different TimeZone, it's even simpler than that.
Calendar ret = Calendar.getInstance(timeZone);
ret.setTime(calendar.getTime());
return ret;
But I'm not sure that will be sufficient for what you need. Whenever you input or output that Calendar (or its Date), the standard Java APIs will automatically convert the value back into local time. JDBC statements (although that could also depend on your particular JDBC driver), toString(), etc. For instance, instead of setting the Calendar's TimeZone, you may need to actually use DateFormat with a TimeZone.
If your Web Service engine is automatically converting an incoming "date" type field to Calendar, you may have some options there, particularly if the type of the field is a true date format rather than a plain string.
Difficult to say more without knowing how you need to use this TimeZone-converted Calendar.
精彩评论