Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

JavaWorld Daily Brew

Java's TimeZone and Calendar classes not working correctly for me



So, I was given some data in UTC time, and needed to convert it to Pacific Standard Time (well, technically Pacific Daylight Time now.) I did this like so:

//given in UTC - this needs to be converted to local time
GregorianCalendar current = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
current.set(year, monthInt, day, hour, min, sec);

//convert from UTC to PST
cal = new GregorianCalendar(TimeZone.getTimeZone("America/Los_Angeles"));
cal.setTimeInMillis(current.getTimeInMillis());

//reset the fields - have changed now that timezone has changed
year = cal.get(Calendar.YEAR);
monthInt = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DATE);
hour = cal.get(Calendar.HOUR_OF_DAY);
min = cal.get(Calendar.MINUTE);

Now, this works perfectly on my computer at home, does exactly what I want it to do. However, when it was uploaded to the server where it's going to be run, everything's back to UTC time.

My best guess, from reading an article on Java World, is that this is b/c Java (on the server) didn't recognize the TimeZone ID it was given, so reverted back to GMT/UTC time. However, I can't imagine why this would be, especially as America/Los_Angeles is the example time zone given in the JavaDocs, even, and I don't know what else would even be used for Pacific Time.

I'm not sure what else it could be. Do I need to have the Locale specified in addition to the TimeZone? Do I need to set the default TimeZone?

I can't really test this, which makes it more frustrating, as I need to send the code to somebody, so they can upload it to the server, and the turnaround could be a couple days. Thus, I'd like to see if I can fix the problem the first time.

Thanks!