【发布时间】:2018-08-12 11:24:16
【问题描述】:
我打算按照以下逻辑将 ZonedDateTime 转换为即时。
说,我在 PST 时区,当前时间是上午 11 点。如果我现在转换(截至 2018 年 3 月 4 日没有夏令时)并且 toInstant 将是晚上 7 点。
对于同样的上午 11 点,toInstant 将在 2018 年 4 月 4 日下午 6 点返回,因为将遵守夏令时。
所以,下面的代码正确返回。
ZonedDateTime dateTime = ZonedDateTime.now(); --->>> March 04th 2018 at 11 A.M PST
dateTime.plusMonths(1).toInstant(); -->> returns April 04th 2018 at 6 PM PST as daylight saving will be observed
但是,
如果我转换为 Instant 然后添加一个月,结果会有所不同。
Instant dateTime = ZonedDateTime.now().toInstant(); --->>> March 04th 2018 at 7 P.M UTC
dateTime.plus(1,ChronoUnit.MONTHS).toInstant(); -->> returns April 04th 2018 at 7 PM UTC ( but the actual time should be 6 PM UTC ).
这没关系,因为我们已经转换为 UTC,它只是从那里添加。
因此,要包括夏令时,我需要在 ZonedDateTime 中添加天、月或年 ....,然后转换为 Instant。
ZonedDateTime dateTime = ZonedDateTime.now(); ---> March 04th 2018 at 11A.M
dateTime.plusDays(10).toInstant(); ---> March 14th 2018 at 6P.M
dateTime.plusMonths(1).toInstant(); ---> April 04th 2018 at 6P.M
上面的代码按预期工作。但是下面的不是返回 6P.M,而是返回 7P.M.
dateTime.plusSeconds(org.joda.time.Period.days(1).multipliedBy(10).toStandardSeconds().getSeconds())
.toInstant()) --> ---> March 14th 2018 at 7P.M
不确定,这有什么问题以及如何让它在几秒钟内工作。
【问题讨论】:
-
没有
ZoneDateTime类和Period没有publicdays工厂方法。您使用的不是 Java 的 API 吗?也没有toStandardSeconds方法。 -
对不起,错字,...它是 ZonedDateTime 和 Period 来自 joda.time。立即更新问题。
-
这更有意义,但是像这样混合两个 API 必然会产生意想不到的结果。我建议您尝试使用 just Java 的 API 重新创建问题。
-
由于其他一些限制,我正在使用 joda.time。
-
这可以仅使用 Java 8 java.time 方法重现。调用
Instant plusTenDaysInSeconds = zonedDateTime.plusSeconds(Duration.ofDays(10).getSeconds()).toInstant();得到 2018-03-14T19:00:00Z,但调用Instant plusTenDays = zonedDateTime.plusDays(10).toInstant();得到 2018-03-14T18:00:00Z。