1

嗨,我正在尝试将 UTC 偏移量发送到我的服务器。所以我使用以下代码将设备时区转换为 utc 偏移量

    TimeZone tz = TimeZone.getDefault();

    Calendar cal = GregorianCalendar.getInstance(tz);

    int offsetInMillis = tz.getOffset(cal.getTimeInMillis());

    String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));


    Log.d("UTC_Offset",offset);

现在我知道我正在使用 Math.abs 它并没有给我负值,但我真的很愚蠢地知道我怎么能得到那些负时区的偏移量,比如 GMT-07:00 的蒂华纳

注意:我可能对 UTC 中的偏移量有误,但我在 SO 上找到了这个解决方案。请让我知道是否有任何解决方案,或者如果我的想法有误并且UTC不能为负数,请纠正我

4

2 回答 2

1

用于SimpleDateFormat为您格式化:

String offset = new SimpleDateFormat("Z").format(new Date());
offset = offset.substring(0, 3) + ":" + offset.substring(3);

 

        ↓↓↓↓↓如果令人困惑,请忽略其他答案↓↓↓↓↓</p>

 

应用于 Java VM 中的所有 TimeZone 时的结果:

-12:00
-11:00
-10:00
-09:30
-09:00
-08:00
-07:00
-06:00
-05:00
-04:00
-03:00
-02:30
-02:00
-01:00
+00:00
+01:00
+02:00
+03:00
+04:00
+04:30
+05:00
+05:30
+05:45
+06:00
+06:30
+07:00
+08:00
+08:45
+09:00
+09:30
+10:00
+10:30
+11:00
+12:00
+12:45
+13:00
+14:00

打印上述内容的 Java 8 代码:

Instant now = Instant.now();
SimpleDateFormat fmt = new SimpleDateFormat("Z");
ZoneId.getAvailableZoneIds().stream()
    .map(z -> ZoneId.of(z).getRules().getOffset(now))
    .distinct()
    .sorted(Comparator.reverseOrder())
    .forEach(z -> {
        fmt.setTimeZone(TimeZone.getTimeZone(z));
        String offset = fmt.format(Date.from(now));
        offset = offset.substring(0, 3) + ":" + offset.substring(3);
        System.out.println(offset);
    });
于 2020-04-08T08:26:15.297 回答
0
于 2020-04-08T19:22:28.020 回答