You don’t want that.
- You want the same instant, the same point in time. So convert your
OffsetDateTime
to a different offset adjusting the time of day to take into account that the time of day at the new offset is different.
- For most purposes you don’t want to specify the offset to convert to directly. Instead specify which time zone you want to convert to. Let Java find the correct offset for that time zone for that day for you.
The Z
means offset zero from UTC. It is sometimes called “Zulu time zone” even though it’s an offset, not a time zone.
Convert the time to a different time zone
For example:
OffsetDateTime date = OffsetDateTime.parse("2020-03-02T14:25:54.871Z");
ZoneId newZone = ZoneId.of("Europe/Prague");
OffsetDateTime dateAtNewOffset
= date.atZoneSameInstant(newZone).toOffsetDateTime();
System.out.println(dateAtNewOffset);
Output from this piece of code is:
2020-03-02T15:25:54.871+01:00
Please note that the hour of day is now 15 instead of 14 to compensate for the different offset. When the time is 14:25 UTC, it is 15:25 in Prague (except when summer time (DST) is in effect; Java will handle that for you too if you have a date in the summer time part of the year).
To specify offset
If you did want to specify the offset yourself:
ZoneOffset newOffset = ZoneOffset.ofHours(1);
OffsetDateTime dateAtNewOffset = date.withOffsetSameInstant(newOffset);
The result is the same as before.
To add 1 hour to the offset without changing the hour of day
To answer the question that you ask. I repeat my warning, THIS IS NOT WHAT YOU WANT.
ZoneOffset oldOffset = date.getOffset();
ZoneOffset newOffset = ZoneOffset.ofTotalSeconds(Math.toIntExact(
oldOffset.getTotalSeconds() + Duration.ofHours(1).getSeconds()));
OffsetDateTime dateAtNewOffset = date.withOffsetSameLocal(newOffset);
Now the output resembles what you asked for:
2020-03-02T14:25:54.871+01:00