Manoj
Manoj

Reputation: 5602

Java Calendar: getting time for the timezone

The following works (shows UTC time)

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
System.out.println(new Date());

but this doesn't (shows local time)

    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    System.out.println(cal.getTime());
    System.out.println(new Date());

Is there something simple, that I'm missing?

Upvotes: 3

Views: 7723

Answers (2)

Andrei Petrenko
Andrei Petrenko

Reputation: 3950

To get date, formatted for other timezone, use SimpleDateFormat and set timezone in it (by default, it uses local timezone).

Try this way:

SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyyy HH:mm:SS Z");
f.setTimeZone(TimeZone.getTimeZone("UTC"));
Calendar cal = Calendar.getInstance();
System.out.println(f.format(cal.getTime()));
System.out.println(new Date());

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1499770

You're printing out the result of Date.toString(), which always uses the default time zone.

I suggest you use DateFormat instead, which is better suited for formatting dates. Date.toString is really only suitable for debugging - it provides no control over the format.

Alternatively, use Joda Time for all your date and time operations - it's a much better API to start with :)

Upvotes: 7

Related Questions