How to set required timezone in LocalTime
from joda? Required timezone - Moscow.
Default constructor new LocalTime()
shows other time for me: it shows time, which is one hour ahead then in my timezone.
Set LocalTime joda
229 views Asked by pragmus At
2
There are 2 answers
0
On
A LocalTime
doesn't have a time zone. That's the whole point of it.
If you want the LocalTime
for a particular instant in a particular time zone, you can use DateTime
and then toLocalTime
:
DateTime now = new DateTime(zone); // Urgh: see below
LocalTime localNow = now.toLocalTime();
Note that I would strongly advise having a dependency representing a clock to provide "the current instant" - you can then use a "system" implementation returning the current time via System.currentTimeMillis
or the like, but you can also use a "testing" implementation returning a predefined time, allowing you to write unit tests for any moment in time that you like.
With such a dependency, you'd probably have something like:
DateTime now = new DateTime(clock.getCurrentInstant(), zone);
LocalTime localNow = now.toLocalTime();
Jon Skeets advise about an injectable clock is nice and good. Otherwise - and closer to your question - you should use the alternative constructor of
LocalTime
accepting aDateTimeZone
-argument in order to not rely on your system timezone which might not be what you want:How does it work?
First Joda-Time uses the standard system clock via
System.currentTimeMillis()
and gets a global timestamp. In order to derive the local time part Joda-Time must know a timezone reference. That is what you define here. The zone is only used for the conversion, nothing else. After the construction of the new local time (which has no internal knowledge about timezones), Joda-Time no longer needs the zone reference as documented.Update:
In case your system timezone is already "Europe/Moscow" (the constructor without args uses the system tz!) you should check your Joda-Time-version. Maybe you have outdated timezone data containing old dst rules. Downloading the newest version v2.8 would probably help against old data.