Our application uses jodatime to handle times, and (for API formatting reasons) we store times in a model class which looks a bit like this:
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
}
Further downstream I noticed we were getting a different time out than we were setting. I figured we were converting the fields back to a DateTime wrong, since the local fields seem to have the right values.
On a whim I tried changing the getter and now it works, but I have no idea why:
public DateTime getTime() {
return localStopTime.toDateTime().withZone(timeZone);
}
The joda documentation is a bit tight-lipped about how it carries out the toDateTime()
call; it says it "uses" a certain timezone somehow but that's it.
Can anyone explain to me what the difference is between
return localStopTime.toDateTime(timeZone);
and
return localStopTime.toDateTime().withZone(timeZone);
?
Thanks in advance!
Edit: I've figured it out - I was using "Etc/GMT" as my time zone and that didn't take into account daylight savings. Have marked Marco's answer as correct
The difference between those two is the next one, you use withZone()
to: (as JavaDocs says)
Returns a copy of this datetime with a different time zone, preserving the millisecond instant.
Also, the JavaDocs provides a good example:
This method is useful for finding the local time in another timezone. For example, if this instant holds 12:30 in Europe/London, the result from this method with Europe/Paris would be 13:30.
And you use the toDateTime(timeZone)
to return a DateTime
object but applying the specified timeZone
to it.
So, you can use toDateTime(timeZone).withZone(secondTimeZone)
and you will get a copy of the DateTime
generated by the first statement (toDateTime(timeZone)
) but, with a different time zone, perseving the milisecond instant. And if you use toDateTime()
with no parameters, will only retrieve a DateTime
object.