Reputation: 92
I have a Method which parses a String according to Iso8601 and returns a LocalDateTime. Now I accept possible offsets. The Problem now is I have to convert the offset to UTC and return it as LocalDateTime.
So far I have tried working with Instant, OffsetDateTime, ZonedDateTime. I always get the opposite. Instead of +06:00 my result will be shown as -06:00.
return LocalDateTime.ofInstant(Instant.from(OffsetDateTime.parse(date, buildIso8601Formatter())), ZoneOffset.UTC);
This is the solution which works the same as my other tried ones I mentioned above.
I know this is not the common way to do it and I did a lot of research because of that but the current architecture only allows me to do it that way.
EDIT example: With an implementation like this:
OffsetDateTime offsetDateTime = OffsetDateTime.parse(date, buildIso8601Formatter());
Instant instant = offsetDateTime.toInstant();
return LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
Let's say I get "2020-01-12T08:30+06:00"
as input for my method. I HAVE to return LocalDateTime.
As a result I want to have "2020-01-12T14:30"
instead my best solution was to get it the opposite way: "2020-01-12T02:30"
.
Upvotes: 1
Views: 756
Reputation: 22977
The behavior of java.time
is correct. The string 2020-01-12T08:30+06:00
means that the datetime part of this string is a datetime local to some region, which exists in an area with an offset of +06:00
from UTC.
Your interpretation is different from the abovementioned case. In your case, you interpret 08:30
as a time in sync with UTC, and then concatenate the timezone offset string for the desired region.
So if you really want to do this – think again.
One way to achieve this, is simply by parsing the datetime as an offset datetime and negate the offset.
Upvotes: 4