OffsetDateTime 到 ZonedDateTime - 具有特定的 ZoneId

OffsetDateTime to ZonedDateTime - with specific ZoneId

我们创建了一个 DateTime class 来在我们的库中保存日期时间。该值通常来自 SQL 数据库(因此 UTC)或 XML(可以有偏移量)。但它也可以是具有明确时区的日期时间(如丹佛)。

在我们的 class 中,我们将其保存为 OffsetDateTime,我认为这是最好的,因为 98% 的时间我们得到一个具有已知偏移量且没有区域的显式瞬间。

当它用 ZonedDateTime 初始化时,我想我们将它保存为 OffsetDateTime 并保存 ZoneId。然后,仅在我们需要 ZonedDateTime 对象(转换为字符串以供显示)的情况下,如果我们有 ZoneId,则将其应用于 OffsetDateTime.toZonedDateTime()。这样我们得到 "MST" 而不是 'z' 值的“-0700”显示为字符串。

如何从 OffsetDateTime 创建具有特定 ZoneId 的 ZonedDateTime?

针对您提出的具体问题的解决方案;

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

但是,我不确定您为什么要在 OffsetDateTime 中保存时间戳。如果你跟踪你的 ZoneId,你可以在 UTC 中保存时间戳,并在 backend/frontend(或任何其他客户端)中转换为你希望的任何格式。将日期时间存储为 UTC 会给你更多的灵活性。