问题
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