Java 8将UTC时间转换为EDT/EST,使日期保持不变

3

我在Java中使用ZonedDateTime变量。

我希望将变量的值(默认UTC时区)转换为“America/New York”的时区,使日期保持不变。

例如:4:00 am UTC = 12:00 am EST。通过添加或减去小时数来更改ZonedDateTime变量,以使日期保持不变。

我们如何实现这种转换呢?


当你说“date 没有变化”时,你实际上是指“time 没有变化”吗?例如,7月5日凌晨2点应该保持为7月5日凌晨2点。还是你的意思是时间应根据时区更改进行调整,但是 date 不应更改?例如,7月5日凌晨2点不应该是7月4日晚上10点,而应该是7月5日晚上10点。 - Andreas
我也不明白。你是想把4 AM UTC转换成12点午夜EDT还是4 AM EDT?只有后者在所有情况下都能保留日期(日期指年、月和日)。 - Ole V.V.
4个回答

3

您可以通过将时间转换为LocalDateTime,然后再转换回指定时区的ZonedDateTime来完成:

ZonedDateTime zoned = ZonedDateTime.now();
LocalDateTime local = zoned.toLocalDateTime();
ZonedDateTime newZoned = ZonedDateTime.of(local, ZoneId.of("America/New_York"));

2

如果你想将UTC日期和EST时间结合起来,可以按照以下方式进行:

ZonedDateTime utc = ...

ZonedDateTime est = utc.withZoneSameInstant(ZoneId.of("America/New_York"));

ZonedDateTime estInSameDay = ZonedDateTime.of(utc.toLocalDate(), est.toLocalTime(), ZoneId.of("America/New_York"));

1
如果时区信息对于您的UTC时间不是必需的,那么最好使用Instant类。使用Instant对象,您可以轻松地转换为指定时区的ZonedDateTime
Instant instant = Instant.parse("2018-10-02T04:00:00.0Z");
ZonedDateTime nyTime = instant.atZone(ZoneId.of("America/New_York")); 
//2018-10-02 00:00:00

0

保持您的日期不变,我认为这可能有效

    ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC);
    ZonedDateTime est = utc.plusHours(5); //normally est is 5 hours ahead

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接