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;
}
Answer
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.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM