2012-06-11 39 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

相关问题