格式为GMT/UTC时间,默认时区为其他时间

pst*_*ton 6 java timezone date

由于其他原因,我有一个需要在我当地时区运行的程序,但对于一个程序,我需要在GMT中使用SimpleDateFormat输出日期.

最简单的方法是什么?

McD*_*ell 10

使用标准API:

Instant now = Instant.now();
String result = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)
                                 .withZone(ZoneId.of("GMT"))
                                 .format(now);
System.out.println(result);
Run Code Online (Sandbox Code Playgroud)

新的DateTimeFormatter实例是不可变的,可以用作静态变量.

使用旧的标准API:

TimeZone gmt = TimeZone.getTimeZone("GMT");
DateFormat formatter = DateFormat.getTimeInstance(DateFormat.LONG);
formatter.setTimeZone(gmt);
System.out.println(formatter.format(new Date()));
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 8

鉴于这SimpleDateFormat不是线程安全的,我会说最整洁的方法是使用Joda Time.然后你可以创建一个格式化程序(调用withZone(DateTimeZones.UTC)以指定你想要UTC)并且你离开了:

private static DateTimeFormatter formatter = DateTimeFormat.forPattern(...)
    .withZone(DateTimeZone.UTC);

...

String result = formatter.print(instant);
Run Code Online (Sandbox Code Playgroud)

这有另一个好处,你可以在代码中的其他地方使用Joda Time,这总是一件好事:)