我们的应用程序使用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时出现了错误,因为本地字段似乎具有正确的值。
出于一时兴起,我尝试更改getter,现在它可以工作了,但我不知道原因是什么:
public DateTime getTime() {
return localStopTime.toDateTime().withZone(timeZone);
}
Joda文档 对于如何执行toDateTime()
调用有点保密; 它说它以某种方式 "使用" 特定的时区,但仅此而已。
有人能解释一下这两者之间的差异吗?
return localStopTime.toDateTime(timeZone);
并且
return localStopTime.toDateTime().withZone(timeZone);
谢谢您提前的帮助!
编辑:我已经解决了 - 我使用的是“Etc / GMT”作为我的时区,这没有考虑到夏令时。已将Marco的答案标记为正确。
return localStopTime.toDateTime(timeZone);
我得到了相同的DateTime
。而使用return localStopTime.toDateTime().withZone(timeZone);
我得到了一个不同的结果(除非提供的DateTime
的时区是我的默认时区)。我观察到的也符合我的预期行为。 - Ole V.V.new DateTime(DateTimeZone.forID("Asia/Shanghai"))
(我的本地时区是欧洲/哥本哈根)。我怀疑你们这边可能出了一些意外情况,但我无法猜测具体是什么。 - Ole V.V.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。 - Ole V.V.