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

泪湿孤枕 提交于 2019-12-10 14:57:13

问题


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;
}

回答1:


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



来源:https://stackoverflow.com/questions/49790409/how-to-make-zoneoffset-utc-return-0000-instead-of-z

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!