2012-06-11 43 views
1

我想將當前日期轉換爲美國/蒙特利爾時區。我這樣做:Java將日期轉換爲EST時區以尊重DST

Date date = new Date(); 
TimeZone timeZone = TimeZone.getTimeZone ("America/Montreal"); 
Calendar cal = new GregorianCalendar(timeZone); 
cal.setTime(date); 
String whatIWant = "" + cal.get(Calendar.HOUR_OF_DAY) + ':'+ 
        cal.get(Calendar.MINUTE)+ ':'+ cal.get(Calendar.SECOND); 

log.info(whatIWant); 

轉換是很好,但我想知道這個代碼是多麼強大。在沒有夏令時會發生什麼?

+0

你說*忽略*使用已過時的API,但它們在這裏顯然是相關的,因爲'Date'構造函數使用當前時區。完全不清楚問題是什麼。另外,爲什麼你不使用SimpleDateFormat? –

回答

6

該代碼很好。 Java會自動將冬令時或夏令時考慮在內。

您還可以通過使用DateFormat對象的日期轉換爲字符串做到這一點,設置所需的時區DateFormat對象:

Date date = new Date(); 

DateFormat df = new SimpleDateFormat("HH:mm:ss"); 

// Tell the DateFormat that you want the time in this timezone 
df.setTimeZone(TimeZone.getTimeZone("America/Montreal")); 

String whatIWant = df.format(date); 
+0

謝謝,你的前兩句回答我的問題!你有什麼想法,爲什麼,當我手動設置日期時,轉換是在EDT而不是EST再次完成的? – gpol

+1

@gpol因爲12月28日是冬令時(EDT),而不是夏令時(EST)。 – Jesper

+0

難道不是這樣嗎?我的意思是夏季時不是EDT而冬季是EST? – gpol

相關問題