2013-03-20 64 views

回答

2

我不確定這個原因,但他們確實爲您提供了一個getAvailableIDs()方法,可以讓您確保您的時區爲vaild。他們在javadoc中提到了這一點:

您可以使用getAvailableIDs方法來遍歷所有支持的時區標識的 。然後你可以選擇一個支持的ID來獲得一個 時區。如果您想要的時區不被 支持的ID之一表示,那麼自定義時區ID可以被指定生產 一個TimeZone

1

一個爪哇類似這種困境的原因(即一根絕特別注意避免依賴系統的缺省語言環境,字符集和時區,在字符轉換失敗時讀取文本文件或寫入文本文件失敗,因爲磁盤已滿等情況下可能會出現異常)等等)可能是Java was first applied for programming user interfaces,而不是服務器後端:在用戶界面中,顯示錯誤輸出可能比完全失敗更好,因爲用戶通常可以找出錯誤並正確解釋現有輸出。儘管如此,我認爲在TimeZone.getTimeZone(String)中省略例外是一個設計錯誤。

無論如何,現在有新的更好的API可用。獲得時區(從Java 8開始)的現代方式是

TimeZone.getTimeZone(ZoneId.of(zoneId)); 

哪個確實會爲無效區域標識引發異常。 ZoneId.of(String)接受的區域ID格式與TimeZone.getTimeZone(String)不完全相同,但the Javadoc of ZoneId.of(String)表示大多數區域ID是兼容的。

+0

還沒有遇到'ZoneId'。看起來很有希望。謝謝! – armandino 2015-03-05 04:53:42

0

以@ Jaan的答案爲基礎,建議使用ZoneId.of()。這裏有一種方法可以避免ZoneId的ID與TimeZone的ID不完全相同的事實:首先使用TimeZone.getAvailableIDs()來檢查提供的時區ID是否爲像「Europe/Rome」這樣的字符串,第二次使用ZoneId.of( )如果它是一個固定的偏移ID,否則它是無效的。

/* Returns null if the timezoneID is invalid */ 
private static TimeZone getTimeZone(String timezoneID) { 

    final String[] availableTimezoneIDs = TimeZone.getAvailableIDs(); 

    if (! Arrays.asList(availableTimezoneIDs).contains(timezoneID)) { 

     // Unknown timezone ID, maybe a fixed offset timezone id? 

     if (timezoneID.equals("Z") || 
       timezoneID.startsWith("+") || timezoneID.startsWith("-") || 
       timezoneID.startsWith("UTC") || timezoneID.startsWith("UT") || timezoneID.startsWith("GMT") 
       ) { 
      try { 
       return TimeZone.getTimeZone(ZoneId.of(timezoneID)); 
      } catch (DateTimeException e) { 
       // Invalid fixed-offset timezone id 
       return null; 
      } 
     } else 
      // Not even a fixed offset timezone id 
      return null; 

    } else 
     return TimeZone.getTimeZone(timezoneID); 

} 
相關問題