【问题标题】:Java 8 Convert UTC time to EDT/EST so that date remains the sameJava 8 将 UTC 时间转换为 EDT/EST 以便日期保持不变
【发布时间】:2019-03-07 05:12:11
【问题描述】:

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

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

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

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

【问题讨论】:

  • 当你说“date is not changed”时,你的意思是“time is not changed”吗?例如。凌晨 2 点的 7/5 应该保持在凌晨 2 点的 7/5。 --- 或者你的意思是应该根据时区变化调整时间,但不应该改变date?例如。凌晨 2 点的 7/5 不应是晚上 10 点的 7/4,而是晚上 10 点的 7/5。
  • 我也没明白。您想将 UTC 凌晨 4 点转换为美国东部时间午夜 12 点还是美国东部时间凌晨 4 点?只有后者会在所有情况下保留日期(日期为年、月和月日)。

标签: java datetime java-8 timezone zoneddatetime


【解决方案1】:

您可以通过转换为 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"));
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        如果您的 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
        

        【讨论】:

          猜你喜欢
          • 2014-01-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-07
          • 1970-01-01
          • 2020-12-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多