【发布时间】:2019-08-16 19:53:30
【问题描述】:
我们的应用程序使用 jodatime 来处理时间,并且(出于 API 格式的原因)我们将时间存储在一个看起来有点像这样的模型类中:
class Event {
private LocalDateTime localTime;
private DateTimeZone timeZone;
public DateTime getTime() {
return localStopTime.toDateTime(timeZone);
}
public void setTime(DateTime value) {
this.localTime = value.toLocalDateTime();
this.timeZone = value.getZone();
}
// ...more boilerplate
}
在下游,我注意到我们得到的超时时间与我们设置的不同。我认为我们将字段转换回 DateTime 是错误的,因为本地字段似乎具有正确的值。
一时兴起,我尝试更改吸气剂,现在它可以工作了,但我不知道为什么:
public DateTime getTime() {
return localStopTime.toDateTime().withZone(timeZone);
}
joda documentation 对它如何执行toDateTime() 调用有点守口如瓶;它说它以某种方式“使用”了某个时区,但就是这样。
谁能解释一下两者的区别
return localStopTime.toDateTime(timeZone);
和
return localStopTime.toDateTime().withZone(timeZone);
?
提前致谢!
编辑:我已经弄清楚了 - 我使用“Etc/GMT”作为我的时区,并且没有考虑夏令时。已将 Marco 的答案标记为正确
【问题讨论】:
-
jodatime 是开源的!查看LocalDateTime:getDateTime() 和DateTime:withZone() 的来源,以准确了解发生了什么。
-
我的观察与你的相反。有了
return localStopTime.toDateTime(timeZone);,我确实得到了同样的DateTime。随着return localStopTime.toDateTime().withZone(timeZone);我得到一个不同的(除非提供的DateTime的区域是我的默认时区)。我所观察到的也符合我对预期行为的理解。 -
@OleV.V. - 这很有趣 - 我能问一下你用的是什么时间吗?我正在使用 localTime=2014-04-24T15:55:00.000, timeZone=Etc/GMT 进行测试,即在夏令时。
-
我使用了国外时区的当前时间:
new DateTime(DateTimeZone.forID("Asia/Shanghai"))(我自己的时区是欧洲/哥本哈根)。我怀疑你身边可能发生了一些计划外的事情,但我猜不出是什么。 -
(1) 我设置的日期时间:
2019-03-28T01:28:26.755+08:00。我从return localStopTime.toDateTime(timeZone);得到的日期时间:相同。 (2) 我设置的日期时间:2019-03-28T01:29:40.414+08:00。我从return localStopTime.toDateTime().withZone(timeZone);得到的日期时间:2019-03-28T08:29:40.414+08:00。请注意,小时数是 08 而不是 01。
标签: java time timezone jodatime