Joda time zone different than JDK's

后端 未结 1 1504
庸人自扰
庸人自扰 2020-12-19 13:55

In my client, I have this code:

System.out.println(\"Java tz: \" + TimeZone.getDefault());
System.out.println(\"Joda tz: \" + ISOChronology.getInstance());
<         


        
相关标签:
1条回答
  • 2020-12-19 14:36

    When you say "defaults read from the OS & local system", there isn't a single, well-defined place to read this default from. Even the API documentation itself says

    Gets the default TimeZone for this host. The source of the default TimeZone may vary with implementation.

    So the simple answer is that Joda and your JVM are inferring the default time zone from different sources of information. The point to remember about this is that the default is a guess, not something that the JVM can definitively get access to.

    For Sun's 1.5.0_06 JVM on Linux, the following order is used:

    1. Looks to environment variable TZ
    2. Looks for the file /etc/sysconfig/clock and tries to find the "ZONE" entry.
    3. Compares contents fo /etc/localtime with the contents of every file in /usr/share/zoneinfo recursively. When the contents matches, it returns the path and filename, referenced from /usr/share/zoneinfo.

    Joda 1.6.2 uses:

    1. The system property user.timezone.
    2. If the above is null or not a valid identifier, the value of the JDK's TimeZone default is used.
    3. If that fails, UTC is used.

    So if you have the above versions of JDK and Joda, I suggest that the user.timezone property may be set in your environment. Other versions may will use other algorithms to acquire the default, though.

    Edit: In Sun's JDK 1.6.0_22, the default search first inspects the user.timezone property as well, and if that isn't found it looks up the user.country property in order to get the default value for a country. If neither is set, the default of GMT is used. So the results you observe may well change with your JVM version.


    Edit 2: If you've got the source to both (and indeed the sources are both available), then you can simply trace it! Step through the Joda call, to see if it does indeed defer to java.util.TimeZone.getDefault(), and see what the returned value is. Then invoke the JDK method directly and see what you get.

    Looking at the JDK sources, it seems that the default timezone is accessed via an inheritable thread local. Thus if someone somewhere calls TimeZone.setDefault(), it may or may not be visible in other threads, depending on whether they've looked up the version already. If you're getting apparently anomalous results from debugging the calls, it could well be simply due to the fact that different threads can have different default TimeZones.

    0 讨论(0)
提交回复
热议问题