5

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().

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Greg
  • 10,696
  • 22
  • 68
  • 98

3 Answers3

12

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
azro
  • 53,056
  • 7
  • 34
  • 70
0

This will shift the time zone from current/now:

someOffsetDateTime.withOffsetSameInstant(OffsetDateTime.now().getOffset())
Greg
  • 10,696
  • 22
  • 68
  • 98
  • 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 offsets – user1708042 Mar 28 '22 at 15:14
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

user1708042
  • 1,740
  • 17
  • 20