繁体   English   中英

Java将日期转换为EST时区以遵守DST

[英]Java convert date to EST timezone to respecting 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM