Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make ZoneOffset UTC return "+00:00" instead of "Z"

Is there any built-in method in java to return "+00:00" for ZoneOffset UTC? The getId() method only return "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;
}
like image 477
Hai Hoang Avatar asked Apr 12 '18 07:04

Hai Hoang


People also ask

What is ZoneOffset UTC?

ZoneOffset extends ZoneId and defines the fixed offset of the current time-zone with GMT/UTC, such as +02:00. This means that this number represents fixed hours and minutes, representing the difference between the time in current time-zone and GMT/UTC: LocalDateTime now = LocalDateTime.

What is ZoneId for UTC?

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime . There are two distinct types of ID: Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times.


1 Answers

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

like image 113
Ole V.V. Avatar answered Oct 03 '22 14:10

Ole V.V.