gpo*_*pol 1 java timezone datetime
我想将当前日期转换为美国/蒙特利尔时区.我是这样做的:
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);
Run Code Online (Sandbox Code Playgroud)
转换很好,但我想知道这段代码有多强大.没有夏令时会发生什么?
那段代码很好.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);
Run Code Online (Sandbox Code Playgroud)