如何使 ZoneOffset UTC return "+00:00" 而不是 "Z"
How to make ZoneOffset UTC return "+00:00" instead of "Z"
在 java 到 return "+00:00"
中是否有针对 ZoneOffset
UTC 的内置方法? getId()
方法仅 return "Z"
.
我目前的方法是手动将其更改为 "+00:00"
如果结果是 "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'。”宾果。
在 java 到 return "+00:00"
中是否有针对 ZoneOffset
UTC 的内置方法? getId()
方法仅 return "Z"
.
我目前的方法是手动将其更改为 "+00:00"
如果结果是 "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'。”宾果。