tags:

views:

230

answers:

2

Hi

I am trying to instantiate GregorianCalendar with TimeZone GMT, but whenever I call the getTime() method, it gives me time in local TimeZone. Here is my code:

Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
System.out.println(cal.getTime());

The output I am getting is this:

Sat Nov 28 19:55:49 PKT 2009

Please help!

+6  A: 

The problem is not with GregorianCalendar but with Date, which is being used to format the date/time for toString for println.

If you want control of date formatting, you'll need to instantiate your own DateFormat - I always use SimpleDateFormat because I'm rather picky about how I want my dates to look.

If you're not interested in the details of how the date is formatted, you can also use one of the getInstance... factory methods of DateFormat.

You can explicitly setTimeZone on a DateFormat (including SimpleDateFormat, of course).

Carl Smotricz
he is ecplicitely calling `getTime()`, which returns Date, which, as you say, should be avoided.
Bozho
I didn't say that. I said that the way Date formats to a String needs to be avoided.
Carl Smotricz
ah, I understood the "which is being used", with the Calendar being the "doer", but you meant the qustion-author :)
Bozho
Thanks for the clarification. I'm afraid Michael Esther (sp?) had the better idea when he just sat down and showed how to do it.
Carl Smotricz
+6  A: 

I'm not sure if this answers your question, but this is one way to get "now" in GMT.

import java.text.*
import java.util.* 

Calendar cal = new GregorianCalendar();
Date date = cal.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(formatter.format(date));

See the Javadoc on SimpleDateFormat for different patterns. Also, you may want to consider Joda Time as it is far superior for dates and times.

Michael Easter
+1 for providing a nice detailed example to go with my ramblings, and for suggesting Joda Time. java.util.Date and Calendar are an embarrassment to the Java language.
Carl Smotricz
Isn't the preferred way of getting a Calendar: Calendar cal = Calendar.getInstance() ?
kgrad
+1 for Joda Time
Brian Agnew
@kgrad - Calendar is abstract, so you can't do that!
Brian Agnew
@Brian Agnew - Seems to work for me...
kgrad
@Brian: You can't directly instantiate an abstract class, but that doesn't stop you from calling its static methods. Still, I wonder how Calendar knows to return a Gregorian instance? The doc doesn't say, so an implementation is free to return a Mayan calendar??
Carl Smotricz