【问题标题】:GMT Timezone from Zone Id来自区域 ID 的 GMT 时区
【发布时间】:2015-11-15 02:49:49
【问题描述】:

我需要从 Java 中的时区 ID 获取以下格式的 GMT 时区值:GMT+05:30MST-07:00

区域 ID 示例:

String zoneId ="America/Phoenix" or "Asia/Calcutta"

【问题讨论】:

  • 使用TimeZone#getOffset(),然后将毫秒转换为小时来创建一个字符串。

标签: java timezone


【解决方案1】:

我想你指的是java.util.TimeZone

这是一个 Java 7 示例:

public static void main(String[] args) {
    final String id = "America/Phoenix";
    TimeZone timeZone = TimeZone.getTimeZone(id);
    long hours = TimeUnit.MILLISECONDS.toHours(timeZone.getRawOffset());
    long minutes = TimeUnit.MILLISECONDS.toMinutes(timeZone.getRawOffset())
            - TimeUnit.HOURS.toMinutes(hours);
    System.out.println("timeZone(" + id + ") = " + String.format("GMT%02d:%02d", hours, minutes));
}

【讨论】:

  • 这没有提供问题的答案。要批评或要求作者澄清,请在其帖子下方发表评论。
  • 好的,我举了一个例子。
  • @TheThom 你是对的。这没有给出正确的例子。我有相同的 sn-p,它给我的输出为 GMT-7:00,但我希望它为 GMT-07:00
  • @Craig 我已经尝试过字符串格式化程序。它仍然无法正常工作。并且输出将仅为 GMT-7:00
  • 所以你把它从 GMT%d:%02d 改成了 GMT%02d:%02d 还是不行?
【解决方案2】:

这在 Java 8 中对我有用:

LocalDateTime curTime = LocalDateTime.now();

String zoneId ="America/Phoenix";
String gmtZoneId = "GMT" + ZoneId.of(zoneId).getRules().getOffset(curTime);
System.out.println(gmtZoneId); // GMT-07:00 will be printed

【讨论】:

    猜你喜欢
    • 2021-01-03
    • 2023-01-23
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多