views:

220

answers:

2

I know there are other similar questions to this, but I came up with my own way of getting the current time in a specific time zone, so I just wanted to confirm if it is correct or not, or there are gotchas I didn't take care of.

Calendar cal = Calendar.getInstance();

// Assuming we want to get the current time in GMT.
TimeZone tz = TimeZone.getTimeZone("GMT");
cal.setTimeInMillis(calendar.getTimeInMillis()
                    + tz.getOffset(calendar.getTimeInMillis())
                    - TimeZone.getDefault().getOffset(calendar.getTimeInMillis()));

// Calendar should now be in GMT.

Is the above correct at all? I did my own test and it seemed to be working as expected, but just wanted to confirm it again with the experts in Stack Overflow.

+1  A: 

I'd prefer using joda-time instead of that.

Check this link.

Macarse
Sure, I have heard of many great things about joda-time, but I am currently restricted to whatever is provided in by Sun's Java. But thanks anyway, I will definitely give it a shot in the near future.
+4  A: 

If you simply do a Calendar.getInstance with the TimeZone argument, the calendar's internal state for the get() methods will return you the field with the time for that timezone. For example:

 Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
 // if i run this at 9 EST this will print 2
 System.out.println(cal.get(Calendar.HOUR));

If you just need the local time for display purposes, you can set the TimeZone on your format object. For example:

 SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss z");
 sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
 System.out.println(sdf.format(new Date()));

Like Macarse said though, Joda time is where it's at if you need to do anything more complex. The Java date APIs are a nightmare.

Jason Gritman