user826323
user826323

Reputation: 2338

Display time per timezone

I am trying to display current time per timezone like the following, but it doesn't print out the time as expected.

long currentLong = System.currentTimeMillis();
TimeZone.setDefault(TimeZone.getTimeZone("EST"));
System.out.println("EST=="+ new java.util.Date(currentLong).toString());

TimeZone.setDefault(TimeZone.getTimeZone("CST"));
System.out.println("CST=="+ new java.util.Date(currentLong).toString());

TimeZone.setDefault(TimeZone.getTimeZone("MST"));
System.out.println("MST=="+ new java.util.Date(currentLong).toString());

TimeZone.setDefault(TimeZone.getTimeZone("PST"));
System.out.println("PST=="+ new java.util.Date(currentLong).toString());

TimeZone.setDefault(TimeZone.getTimeZone("AST"));
System.out.println("AKST=="+ new java.util.Date(currentLong).toString());

TimeZone.setDefault(TimeZone.getTimeZone("HST"));
System.out.println("HAST=="+ new java.util.Date(currentLong).toString());

When I execute the program I get this:

EST==Sat Nov 03 22:24:02 EST 2012
CST==Sat Nov 03 22:24:02 CDT 2012
MST==Sat Nov 03 20:24:02 MST 2012
PST==Sat Nov 03 20:24:02 PDT 2012
AKST==Sat Nov 03 19:24:02 AKDT 2012
HAST==Sat Nov 03 17:24:02 HST 2012

I am wondering why the time for CST is same as EST and MST and PST are same.

Can somebody tell me what the problem is?

Thanks.

Upvotes: 0

Views: 4066

Answers (2)

Paweł Dyda
Paweł Dyda

Reputation: 18662

The problem is, you are using the wrong class. And of course, you should never set the default time zone.

First, default time zone is the time zone of underlying Operating System. It is OK to use it in the desktop application, but it won't give you valid time for web application. In web application, it is best to ask user what is his/her preferred time zone.

Now, if you want to convert time zone, it is actually quite simple, but you have to use the correct class. The correct class is DateFormat:

Date now = new Date();
// you need to detect locale somehow
// this way is valid with desktop applications only
Locale locale = Locale.getDefault(Locale.Category.FORMAT);
DateFormat df = DateFormat.getDateTimeInstance(
    DateFormat.DEFAULT, DateFormat.DEFAULT, locale);
TimeZone est = TimeZone.getTimeZone("EST");
TimeZone mst = TimeZone.getTimeZone("MST");

df.setTimeZone(est);
System.out.println(df.format(now));
df.setTimeZone(mst);
System.out.println(df.format(now));

As for whether or not, the time zones are the same, you can always ask for their equality:

System.out.println(est.equals(mst));

It is possible that these time zones will be different, but the current offset will be the same. You may query what the offset is like this:

int estOffset = est.getOffset(now);

Upvotes: 0

durron597
durron597

Reputation: 32343

Don't use TimeZone.setDefault(), use Calendar.getInstance(TimeZone tz) and Calendar.setTimeZone(). Date is pretty Deprecated, Calendar is much better.

Upvotes: 2

Related Questions