如何使ZoneOffset UTC返回“ +00:00”而不是“ Z”

Hai*_*ang 5 java timezone-offset

是否有任何内置在Java方法返回"+00:00"ZoneOffsetUTC?该getId()方法仅返回"Z"

我当前的方法是手动将其更改"+00:00"为结果是否为"Z"

public static String getSystemTimeOffset() {
    String id = ZoneOffset.systemDefault().getRules().getOffset(Instant.now()).getId();
    return "Z".equals(id) ? "+00:00" : id;
}
Run Code Online (Sandbox Code Playgroud)

Ole*_*.V. 6

private static DateTimeFormatter offsetFormatter = DateTimeFormatter.ofPattern("xxx");

public static String getSystemTimeOffset() {
    ZoneOffset offset = ZoneId.systemDefault().getRules().getOffset(Instant.now());
    return offsetFormatter.format(offset);
}
Run Code Online (Sandbox Code Playgroud)

事实证明,ZoneOffset可以像日期时间对象一样对a进行格式化(除了没有ZoneOffset.format方法,因此我们需要使用该DateTimeFormatter.format方法并传递区域偏移量)。因此,只需阅读的文档即可DateTimeFormatter。有很多的格式模式字母,您可以使用格式化的偏移量:OXxZ。对于每种格式,我们输入多少格式都会有所不同。大写X将为Z您提供不需要的内容,因此我们可以跳过。这些示例似乎表明我们可以在此处使用小写x或大写形式Z。对于x:“三个字母输出小时和分钟,并带有冒号,例如'+01:30'。” Bingo。

链接:DateTimeFormatter文档