ZonedDateTime无法返回EST时间及Date类型转换问题咨询
问题原因与解决方案
核心问题:Date对象不存储时区信息
java.util.Date本质上只是一个UTC时间戳(记录从1970-01-01 00:00:00 UTC到当前时刻的毫秒数),它本身不包含任何时区数据。当你调用System.out.println(Date)时,Java会自动使用当前JVM的默认时区(你的环境里是IST)来格式化这个时间戳,所以才会显示出IST时间,而非你期望的EST。
你的代码逻辑其实没问题:
ZonedDateTime.now(estZone)确实正确获取了EST时区的当前时间,estTime.toLocalDateTime()能拿到正确的EST本地时间就是证明。estTime.toInstant()转换出的是与EST时间对应的UTC时间戳,这个时间戳是准确的,和EST时刻是同一个时间点,只是时区表示不同。Date.from(estTime.toInstant())创建的Date对象也准确对应了这个时间戳,但打印时被JVM默认时区格式化了,导致显示偏差。
正确的显示方式
如果要输出EST时区的时间,不要直接打印Date对象,而是使用DateTimeFormatter指定时区来格式化:
方法1:直接格式化ZonedDateTime
ZoneId estZone = ZoneId.of("America/New_York"); ZonedDateTime estTime = ZonedDateTime.now(estZone); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy"); System.out.println(estTime.format(formatter));
方法2:格式化Date时指定时区
如果你必须使用Date对象,可以用SimpleDateFormat指定时区:
ZoneId estZone = ZoneId.of("America/New_York"); ZonedDateTime estTime = ZonedDateTime.now(estZone); Date date = Date.from(estTime.toInstant()); SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy"); sdf.setTimeZone(TimeZone.getTimeZone(estZone)); System.out.println(sdf.format(date));
这两种方式都会输出你期望的EST时区格式的时间。
内容的提问来源于stack exchange,提问作者HARI KRISHNA
相关产品推荐
相关产品推荐

