How can I convert Java ZonedDateTime to OffsetDateTime with default time zone offset?
Asked Answered
L

3

6

Say I have a ZonedDateTime of 2018-10-30T18:04:58.874Z : How can I convert this to OffsetDateTime 2018-10-30T13:04:58.874-05:00

I'd prefer the offset to be the default/system offset, for example pulled from OffsetDateTime.now().

Lita answered 30/10, 2018 at 19:35 Comment(1)
What methods of ZonedDateTime do you think can be useful here?Massage
C
13

From your ZonedDateTime you need to specify in which other zone you want your OffsetDateTime, precise the zone and them use .toOffsetDateTime() :

ZonedDateTime z = ZonedDateTime.parse("2018-10-30T18:04:58.874Z");
System.out.println(z); //2018-10-30T18:04:58.874Z

OffsetDateTime o = z.withZoneSameInstant(ZoneId.of("UTC-5")).toOffsetDateTime();
System.out.println(o); //2018-10-30T13:04:58.874-05:00
Collinsia answered 30/10, 2018 at 19:45 Comment(0)
L
0

This will shift the time zone from current/now:

someOffsetDateTime.withOffsetSameInstant(OffsetDateTime.now().getOffset())
Lita answered 30/10, 2018 at 19:46 Comment(1)
This in general seems wrong to me: the offset can change if DST takes place and now() and tha actual date under parse can require different offsetsMiddlesworth
M
0

I think the correct way to do it is as follows:

ZonedDateTime date = ZonedDateTime.parse("2018-10-30T18:04:58.874Z");
ZoneOffset offset = ZoneId.systemDefault().getRules().getOffset(date.toInstant());
ZonedDateTime dateInMyZone = date.withZoneSameInstant(offset)

getting it from now() will give you a possibly wrong result casue the offset can change during the year due to DST

Middlesworth answered 29/3, 2022 at 6:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.