简体   繁体   中英

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

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

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

这会将时区从当前/现在转移:

someOffsetDateTime.withOffsetSameInstant(OffsetDateTime.now().getOffset())

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM