由于其他原因,我有一个需要在我当地时区运行的程序,但对于一个程序,我需要在GMT中使用SimpleDateFormat输出日期。
最简单的方法是什么?
答案 0 :(得分:10)
使用standard API:
Instant now = Instant.now();
String result = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)
.withZone(ZoneId.of("GMT"))
.format(now);
System.out.println(result);
新的DateTimeFormatter实例是不可变的,可以用作静态变量。
使用旧的标准API:
TimeZone gmt = TimeZone.getTimeZone("GMT");
DateFormat formatter = DateFormat.getTimeInstance(DateFormat.LONG);
formatter.setTimeZone(gmt);
System.out.println(formatter.format(new Date()));
答案 1 :(得分:8)
鉴于SimpleDateFormat
不是线程安全的,我会说最整洁的方法是使用Joda Time。然后你可以创建一个格式化程序(调用withZone(DateTimeZones.UTC)
来指定你想要UTC)并且你离开了:
private static DateTimeFormatter formatter = DateTimeFormat.forPattern(...)
.withZone(DateTimeZone.UTC);
...
String result = formatter.print(instant);
这有另一个好处,你可以在你的代码中的其他地方使用Joda Time,这总是是一件好事:)