JodaTime - 将字符串直接传递给DateTime的构造函数 [英] JodaTime-Passing a string directly to DateTime's constructor
问题描述
我在CEST时区(+2),我有一些困难了解JodaTime如何存储DateTime。代码如下:
I'm on CEST timezone (+2) and I'm having some difficulties understanding how JodaTime stores DateTime. Take this code:
String timeString = "2012-09-10T13:30:00+01:00";
DateTime ddateTime = new DateTime(timeString);
DateTime dtLisbon = ddateTime.withZone(DateTimeZone.forID("Europe/Lisbon"));
运行后,变量获取以下值:
After running, the variables get the following values:
timeString = '2012-09-10T13:30:00+01:00'
ddateTime = '2012-09-10T14:30:00.000+02:00'
dtLisbon = '2012-09-10T13:30:00.000+01:00'
为什么JodaTime不将ddateTime设置为我发送的确切字符串?我总是需要调用.withZone方法才能获得正确的时间?
Why doesn't JodaTime set ddateTime to the exact string that I'm sending? Do I always need to call .withZone method to get the right instant?
谢谢
推荐答案
您应该调用一个 DateTime
构造函数,该构造函数需要一个 DateTimeZone
:
You should be calling a DateTime
constructor that takes a DateTimeZone
like so:
new DateTime(timeString, DateTimeZone.forID("Europe/Lisbon"));
如果你逐步通过Joda的通话,我强烈推荐,如何将所有片段组合在一起,您将看到调用链:
If you step through the calls Joda is making, which I highly recommend so you can get a feel for how all the pieces fit together, you'll see that the call chain goes:
DateTime(Object)
-> BaseDateTime(Object, Chronology)
-> AbstractConverter.getChronology(Object, Chronology)
-> DateTimeUtils.getChronology(Chronology)
-> ISOChronology.getInstance()
-> DateTimeZone.getDefault()
-> System.getProperty("user.timezone")
这就是为什么 ddateTime
结束为UTC + 2,这是您的时区,当您不提供 DateTimeZone
而不是UTC + 1,区域。
So that's why ddateTime
ends up being UTC+2, which is your time zone, when you don't provide a DateTimeZone
instead of UTC+1, which is the time zone in the string you provided.
这篇关于JodaTime - 将字符串直接传递给DateTime的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!