3

我在 java 中使用 ZonedDateTime 作为变量。

我想将变量的值(默认 UTC 时区)转换为“美国/纽约”的时区,以使日期保持不变。

示例 UTC 上午 4:00 = 东部标准时间上午 12:00。从 ZonedDateTime 变量中添加或减去小时数,这样日期不会更改。

我们如何才能实现这种转换?

4

4 回答 4

3

您可以通过转换为 LocalDateTime 并返回到具有指定时区的 ZonedDateTime 来做到这一点:

ZonedDateTime zoned = ZonedDateTime.now();
LocalDateTime local = zoned.toLocalDateTime();
ZonedDateTime newZoned = ZonedDateTime.of(local, ZoneId.of("America/New_York"));
于 2018-10-02T05:07:36.243 回答
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"));
于 2018-10-02T04:57:08.637 回答
0

保持你的日期不变,我认为这可行

    ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC);
    ZonedDateTime est = utc.plusHours(5); //normally est is 5 hours ahead
于 2018-10-02T05:01:33.630 回答
0

如果您的 UTC 时间不需要区域信息,那么您最好使用Instant该类来做到这一点。使用Instant对象,您可以轻松地切换到ZonedDateTime指定时区的 a:

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
于 2018-10-02T05:52:14.227 回答