java - Java - 如何将时区转换为不同的格式?
问题描述
在我的 Java 代码中,我的约会具有与每个约会相关的时区。
时区采用以下格式:
Europe/Zurich,
Indian/Antananarivo
我想将这些转换为不同的格式。如何将这些时区转换为例如:
GMT
EST
解决方案
您可以使用 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 日)换了一个小时,但塔那那利佛没有。
推荐阅读
- ms-word - 保存文档后,Word中的自动日期不应更新
- python - Python - 从变量中提取文本块并将其与字符串进行比较
- python - 尝试使用 python 3.5.4 运行时导入 pywinauto.application 会引发错误
- regex - 如果包含查询字符串,则将 url 重定向到新 URL 并传递字符串
- ubuntu - 无法登录到 ec2 实例,因为我将 ubuntu 的 chown 更改为另一个用户
- php - Cpanel 中的 Cron 作业 - 时区问题
- json - 如何将 db 结果行转换为嵌套的 json 格式
- react-native - 如何在本机反应中使用共享代码库制作多个应用程序变体?
- reactjs - 在 Create-React-App 测试套件中运行 axe-core 测试
- vbscript - 使用 WScript.shell 运行 sqlcmd - waitonreturn 不启动