3

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?

Manoj
  • 5,542
  • 9
  • 54
  • 80
  • The `java.util` Date-Time API and their formatting API, `SimpleDateFormat` are outdated and error-prone. It is recommended to stop using them completely and switch to the [modern Date-Time API](https://www.oracle.com/technical-resources/articles/java/jf14-Date-Time.html). Check [this answer](https://stackoverflow.com/a/68056391/10819573) which uses the modern Date-Time API. – Arvind Kumar Avinash Jun 20 '21 at 17:52

2 Answers2

6

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 :)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3

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());
Andrei Petrenko
  • 3,922
  • 3
  • 31
  • 53
  • I need to convert this string date to Date date and if i do, it again picks up the local timezone. Is there any solution for this? – Parkash Kumar Jun 21 '13 at 11:01