Reputation: 32926
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?
Upvotes: 2
Views: 7921
Reputation: 4507
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.
Upvotes: 2