简体   繁体   中英

OffsetDateTime to ZonedDateTime - with specific ZoneId

We have a DateTime class we created to hold a datetime in our library. The value generally comes from a SQL database (so UTC) or XML (can have an offset). But it can also be a datetime with an explicit timezone (like Denver).

Inside our class we hold this as an OffsetDateTime which I think is best because 98% of the time we're getting an explicit instant with a known offset, and no zone.

When it is initialized with a ZonedDateTime, I'm thinking we save it as an OffsetDateTime and save the ZoneId. Then, only for the case where we want a ZonedDateTime object (converting to a string for display), if we have the ZoneId, apply it to OffsetDateTime.toZonedDateTime(). That way we get "MST" instead of "-0700" for the 'z' value in displaying as a string.

How can I create a ZonedDateTime with a specific ZoneId from an OffsetDateTime?

A solution to the specific question you have asked;

ZoneId mst = ZoneId.ofOffset("UTC", ZoneOffset.ofHours(-7));
OffsetDateTime mstOffsetDateTime = OffsetDateTime.now(mst);
ZonedDateTime mstZonedDateTime = mstOffsetDateTime.atZoneSameInstant(mst);

However, I am not sure why you want to save your timestamp in OffsetDateTime . If you keep track of your ZoneId , you could save timestamp in UTC and convert to any format as you wish in backend/frontend (or any other client). Storing datetime as UTC would give you more flexibility.

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