2010-01-18 254 views

回答

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())); 
8

鑑於SimpleDateFormat不是線程安全的,我會說最簡單的方法是使用Joda Time來代替。然後,你可以創建一個單一的格式(調用withZone(DateTimeZones.UTC)來指定要UTC)和你離開:

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

... 

String result = formatter.print(instant); 

這有可以在你的代碼,這是總是使用約達時間在其他地方其他利益一件好事:)

+0

謝謝。好信息。 – pstanton 2010-01-18 23:06:18

+0

@John Skeet在這種情況下線程安全有多遠?我有毫秒的時間,我需要將其轉換爲具有特定格式的UTC字符串。 McDowells的回答不正確嗎? – AgentKnopf 2012-12-20 15:27:21

+0

@Zainodis:如果你很樂意每次都創建一個新的'DateFormat',那很好。就個人而言,我更喜歡喬達時間的方法 - 哎,部分原因是因爲喬達時間只是一個更好的API。 – 2012-12-20 18:19:35

相關問題