JodaTime-Passing a string directly to DateTime's constructor

人走茶凉 提交于 2019-12-12 13:06:09

问题


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'

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?

Thank you


回答1:


You should be calling a DateTime constructor that takes a DateTimeZone like so:

new DateTime(timeString, DateTimeZone.forID("Europe/Lisbon"));

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")

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.



来源:https://stackoverflow.com/questions/12359447/jodatime-passing-a-string-directly-to-datetimes-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!