Java Calendar: getting time for the timezone

后端 未结 2 1864
别跟我提以往
别跟我提以往 2021-01-14 16:17

The following works (shows UTC time)

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

but this doesn\'t

相关标签:
2条回答
  • 2021-01-14 17:05

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

    0 讨论(0)
  • 2021-01-14 17:08

    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());
    
    0 讨论(0)
提交回复
热议问题