如何使ZoneOffset UTC返回"+00:00"而不是"Z" [英] How to make ZoneOffset UTC return "+00:00" instead of "Z"
问题描述
java中是否有任何内置方法为 ZoneOffset
UTC返回"+ 00:00"
? getId()
方法仅返回"Z"
.
Is there any built-in method in java to return "+00:00"
for ZoneOffset
UTC? The getId()
method only return "Z"
.
我当前的方法是手动将结果更改为"Z"
My current approach is manual change it to "+00:00"
if the result is "Z"
public static String getSystemTimeOffset() {
String id = ZoneOffset.systemDefault().getRules().getOffset(Instant.now()).getId();
return "Z".equals(id) ? "+00:00" : id;
}
推荐答案
private static DateTimeFormatter offsetFormatter = DateTimeFormatter.ofPattern("xxx");
public static String getSystemTimeOffset() {
ZoneOffset offset = ZoneId.systemDefault().getRules().getOffset(Instant.now());
return offsetFormatter.format(offset);
}
事实证明,可以像日期时间对象一样设置 ZoneOffset
的格式(除非没有 ZoneOffset.format
方法,所以我们需要使用 DateTimeFormatter.format
方法并传递区域偏移).因此,只需阅读 DateTimeFormatter
的文档即可.您可以使用许多格式模式字母来格式化偏移量: O
, X
, x
和 Z
.对于每种格式,我们输入多少格式都会有所不同.大写的 X
将为您提供您不需要的 Z
,因此我们可以跳过.这些示例似乎表明我们可以在此处使用小写的 x
或大写的 Z
.对于 x
:三个字母输出小时和分钟,并带有冒号,例如'+01:30'."宾果游戏.
It turns out that a ZoneOffset
can be formatted just like a date-time object can (except there is no ZoneOffset.format
method, so we need to use the DateTimeFormatter.format
method and pass the zone offset). So it’s a matter of reading the documentation of DateTimeFormatter
. There are plenty of format pattern letters that you can use for formatting an offset: O
, X
, x
and Z
. And for each it makes a difference how many we put in the format. Uppercase X
will give you the Z
that you don’t want, so we can skip that. The examples seem to indicate that we can use lowercase x
or uppercase Z
here. For x
: "Three letters outputs the hour and minute, with a colon, such as '+01:30'." Bingo.
这篇关于如何使ZoneOffset UTC返回"+00:00"而不是"Z"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!