问题描述
比方说,一周前,我生成了2015-10-10T10:00:00的LocalDateTime。此外,假设我这样生成当前时区ID
Let's say one week ago I generate a LocalDateTime of 2015-10-10T10:00:00. Furthermore, let's assume I generate my current time zone id as such
TimeZone timeZone = TimeZone.getDefault();
String zoneId = timeZone.getId(); // "America/Chicago"
我的zoneId为 America / Chicago。
And my zoneId is "America/Chicago".
有没有一种简便的方法可以将我的LocalDateTime转换为时区ID America / New_York(即,我更新的LocalDateTime为2015-10-10T11:00:00 )?
Is there an easy way I can convert my LocalDateTime to one for the time zone id "America/New_York" (ie so my updated LocalDateTime would be 2015-10-10T11:00:00)?
更重要的是,无论如何,我有没有办法将LocalDateTime转换为东部时间(即,转换为具有zoneId America / New_York的时区)我所在的时区?我特别在寻找一种方法,可以对过去生成的任何LocalDateTime对象执行此操作,而不必在当前时刻为此当前时间执行此操作。
More importantly, is there a way I can convert my LocalDateTime to eastern time (ie, to a time zone with zoneId "America/New_York") no matter what time zone I am in? I am specifically looking for a way to do this with any LocalDateTime object generated in the past, and not necessarily for the current time this instant.
推荐答案
要转换到另一个时区,您首先使用,它返回 ,然后使用,最后将结果转换回 LocalDateTime
。
LocalDateTime oldDateTime = LocalDateTime.parse("2015-10-10T10:00:00");
ZoneId oldZone = ZoneId.of("America/Chicago");
ZoneId newZone = ZoneId.of("America/New_York");
LocalDateTime newDateTime = oldDateTime.atZone(oldZone)
.withZoneSameInstant(newZone)
.toLocalDateTime();
System.out.println(newDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
2015-10-10T11:00:00
如果跳过最后一步,则保留该区域。
If you skip the last step, you'd keep the zone.
ZonedDateTime newDateTime = oldDateTime.atZone(oldZone)
.withZoneSameInstant(newZone);
System.out.println(newDateTime.format(DateTimeFormatter.ISO_DATE_TIME));
2015-10-10T11:00:00-04:00[America/New_York]
这篇关于根据当前时区与东部时区的时差更改LocalDateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!