繁体   English   中英

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

[英]Java 8 Convert UTC time to EDT/EST so that date remains the same

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

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

例如:世界标准时间凌晨4:00 =东部标准时间12:00。 从ZonedDateTime变量中添加或减去小时,以便不更改日期。

我们如何实现这种转换?

您可以通过转换为LocalDateTime并返回指定时区的ZonedDateTime来实现:

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

如果要合并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"));

保持约会不变,我认为这可能有效

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

如果您的UTC时间不需要区域信息,那么使用Instant类会更好。 使用Instant对象,您可以轻松地在指定的时区中ZonedDateTimeZonedDateTime

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM