Why DateTimeZone.getDefault() does not get updated when Zone in Android is changed

我的未来我决定 提交于 2019-12-05 15:28:55

Joda-Time caches the default timezone.

If you run this code (in my JVM, the default timezone is America/Sao_Paulo):

System.out.println("JVM default=" + TimeZone.getDefault().getID()); // America/Sao_Paulo
DateTimeZone t1 = DateTimeZone.getDefault();
System.out.println("Joda Default=" + t1); // America/Sao_Paulo

// setting the default timezone to London
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
System.out.println("JVM default=" + TimeZone.getDefault().getID()); // Europe/London
DateTimeZone t2 = DateTimeZone.getDefault();
System.out.println("Joda Default=" + t2); // America/Sao_Paulo
System.out.println(t1 == t2);  // true

The output will be:

JVM default=America/Sao_Paulo
Joda Default=America/Sao_Paulo
JVM default=Europe/London
Joda Default=America/Sao_Paulo
true

Also note that t1 == t2 returns true, which means they are exactly the same instance.

To set Joda's default timezone after changing the JVM default, you must set it in DateTimeZone too:

// change Joda's default timezone to be the same as the JVM's
DateTimeZone.setDefault(DateTimeZone.forTimeZone(TimeZone.getDefault()));
DateTimeZone t3 = DateTimeZone.getDefault();
System.out.println("Joda Default=" + t3); // Europe/London
System.out.println(t1 == t3); // false

This outputs:

Joda Default=Europe/London
false

After restarting everything, the cache disappears and Joda-Time gets the new default when first called.

You should not directly use Joda-Time but better use the library of Daniel Lew (JodaTimeAndroid - a thin wrapper around Joda-Time) because

  • it has better performance characteristics when loading the tz data on Android
  • it has a suitable broadcast-receiver to track changes of the system timezone.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!