Java将日期转换为EST时区以尊重DST
问题描述:
我想将当前日期转换为美国/蒙特利尔时区。我这样做: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);
转换是很好,但我想知道这个代码是多么强大。在没有夏令时会发生什么?
答
该代码很好。 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);
你说*忽略*使用已过时的API,但它们在这里显然是相关的,因为'Date'构造函数使用当前时区。完全不清楚问题是什么。另外,为什么你不使用SimpleDateFormat? –