private static DateTimeFormatter offsetFormatter = DateTimeFormatter.ofPattern("xxx");
public static String getSystemTimeOffset() {
ZoneOffset offset = ZoneId.systemDefault().getRules().getOffset(Instant.now());
return offsetFormatter.format(offset);
}
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.
Link: DateTimeFormatter
documentation
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…