首页 > 解决方案 > Java - 如何将时区转换为不同的格式?

问题描述

在我的 Java 代码中,我的约会具有与每个约会相关的时区。

时区采用以下格式:

Europe/Zurich,
Indian/Antananarivo

我想将这些转换为不同的格式。如何将这些时区转换为例如:

GMT
EST

标签: javajava-8timezonejava-timegmt

解决方案


您可以使用 ajava.time.ZoneId来解析它们并显示一些相应的短名称:

public static void main(String[] args) throws Exception {
    // example String zones
    String zuerich = "Europe/Zurich";
    String antananarivo = "Indian/Antananarivo";
    // create ZoneIds from the Strings
    ZoneId zueri = ZoneId.of(zuerich);
    ZoneId antan = ZoneId.of(antananarivo);
    // print their short names / abbreviations
    System.out.println(zueri.getDisplayName(TextStyle.SHORT, Locale.ENGLISH));
    System.out.println(antan.getDisplayName(TextStyle.SHORT, Locale.ENGLISH));
}

输出:

CET
EAT

请注意,这CET可能不是很正确,因为它是CEST目前的。

编辑

如果您考虑到一些瞬间,您可以使用 GMT 表示:

public static void main(String[] args) throws Exception {
    // example String zones
    String zuerich = "Europe/Zurich";
    String antananarivo = "Indian/Antananarivo";
    // create ZoneIds from the Strings
    ZoneId zueri = ZoneId.of(zuerich);
    ZoneId antan = ZoneId.of(antananarivo);
    // create a formatter that outputs the GMT+/-XX:XX representations
    DateTimeFormatter gmtFormatter = DateTimeFormatter.ofPattern("OOOO");
    // or take "now" as a temporal reference and print the GMT representation per zone
    ZonedDateTime nowInZurich = ZonedDateTime.now(zueri);
    ZonedDateTime nowInAntananarivo = ZonedDateTime.now(antan);
    System.out.println(nowInZurich.format(gmtFormatter));
    System.out.println(nowInAntananarivo.format(gmtFormatter));
    // find out about the difference when the time switches from daylight saving
    ZonedDateTime sixMonthsLaterInZurich = nowInZurich.plusMonths(6);
    ZonedDateTime sixMonthsLaterInAntananarivo = nowInAntananarivo.plusMonths(6);
    System.out.println(sixMonthsLaterInZurich.format(gmtFormatter));
    System.out.println(sixMonthsLaterInAntananarivo.format(gmtFormatter));
}

印刷

GMT+02:00
GMT+03:00
GMT+01:00
GMT+03:00

看起来苏黎世在六个月后(2021 年 7 月 16 日)换了一个小时,但塔那那利佛没有。


推荐阅读