将 WallClock 时间从一个时区转换为另一个时区

Convert WallClock Time from one timezone to another timezone

我想将挂钟时间从一个 TZ 转换为另一个 我自己不做 OFFSET 数学。

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
    String d = sdf.format(new Date());
    System.out.println(d);
    sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
    String d1 = sdf.format(new Date());
    System.out.println(d1);

输出:

2018.07.09 13:43:30 PDT
2018.07.09 16:43:30 EDT

期望的输出

2018.07.09 13:43:30 PDT
2018.07.09 13:43:30 EDT

如何获得所需的输出?

java.time 和 ThreeTen 向后移植

    DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss z", Locale.US);

    ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
    String d = zdt.format(formatter);
    System.out.println(d);

    zdt = zdt.withZoneSameLocal(ZoneId.of("America/New_York"));
    String d1 = zdt.format(formatter);
    System.out.println(d1);

我运行刚才的代码时的输出:

2018.07.10 04:30:20 PDT
2018.07.10 04:30:20 EDT

您在评论中提到的 ZonedDateTime class 在其 withZoneSameLocal 方法中内置了您想要的转换。这 returns 指定时区的相同挂钟时间。

As of now, we use Java 7. We have not upgraded our infra to java 8…

没什么大问题。 java.time 及其 ZonedDateTime 在 Java 7 上运行良好。他们只需要至少 Java 6.

  • 在 Java 8 和更高版本以及较新的 Android 设备上(据我所知,来自 API 级别 26)现代 API 是内置的。
  • 在 Java 6 和 7 中获取 ThreeTen Backport,新 classes 的 backport(ThreeTen 用于 JSR 310;请参阅底部的链接)。
  • 在(较旧的)Android 使用 ThreeTen Backport 的 Android 版本。它叫做 ThreeTenABP。并确保使用子包从 org.threeten.bp 导入日期和时间 classes。

链接