我有一個程序需要在我的本地時區下運行的其他原因,但對於一個程序,我需要輸出日期使用GMT格式的SimpleDateFormat。格式爲格林尼治標準時間/ UTC時間默認時區是別的
什麼是最乾淨的方法呢?
我有一個程序需要在我的本地時區下運行的其他原因,但對於一個程序,我需要輸出日期使用GMT格式的SimpleDateFormat。格式爲格林尼治標準時間/ UTC時間默認時區是別的
什麼是最乾淨的方法呢?
使用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()));
鑑於SimpleDateFormat
不是線程安全的,我會說最簡單的方法是使用Joda Time來代替。然後,你可以創建一個單一的格式(調用withZone(DateTimeZones.UTC)
來指定要UTC)和你離開:
private static DateTimeFormatter formatter = DateTimeFormat.forPattern(...)
.withZone(DateTimeZone.UTC);
...
String result = formatter.print(instant);
這有可以在你的代碼,這是總是使用約達時間在其他地方其他利益一件好事:)
謝謝。好信息。 – pstanton 2010-01-18 23:06:18
@John Skeet在這種情況下線程安全有多遠?我有毫秒的時間,我需要將其轉換爲具有特定格式的UTC字符串。 McDowells的回答不正確嗎? – AgentKnopf 2012-12-20 15:27:21
@Zainodis:如果你很樂意每次都創建一個新的'DateFormat',那很好。就個人而言,我更喜歡喬達時間的方法 - 哎,部分原因是因爲喬達時間只是一個更好的API。 – 2012-12-20 18:19:35
使用哪個區域? – skaffman 2010-01-18 22:06:58
這是無關緊要的。 – pstanton 2010-01-18 22:26:07