2017-09-15 40 views
4

我审查了与#2时区的许多问题没有得到更新,但我找不到一个的问题,我挣扎:为什么DateTimeZone.getDefault()时区在Android正在改变

  • 为什么Joda的DateTimeZone.getDefault()在TZ更改(在恢复应用程序之后?)时返回更新的时区? TimeZone.getDefault()似乎工作得很好
  • 我应该使用DateTimeZone.forTimeZone(TimeZone.getDefault())来获得最新的Joda的DateTimeZone对象吗?

这里是如何复制:即打印既DateTimeZone.getDefault()TimeZone.getDefault()

  1. 开始应用:

09-15 16:46:59.512 14961-14961/COM .example.android.whatever D/TimeZone: DateTimeZone.getDefault()= Europe/London;TimeZone.getDefault()= libcore.util.ZoneInfo [ID = “欧洲/伦敦”,...]

  • 进入设置 - >时区变化到太平洋夏令时。
  • 回到应用,打印的东西(例如,在的onResume()):
  • 8月9日至15日:49:24.727 14961-14961/com.example.android.whatever d /时区: DateTimeZone.getDefault()=欧洲/伦敦; TimeZone.getDefault()libcore.util.ZoneInfo [ID = “美国/洛杉矶”,...]

  • 在这个阶段I可以旋转应用。 DateTimeZone.getDefault()将被卡住。
  • 只有在应用onRestart后 - 值才会正确。
  • 这是为什么?

    回答

    3

    Joda-Time缓存默认时区。

    如果你运行这段代码(在我的JVM,默认的时区为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 
    

    输出将是:

    JVM默认=美洲/圣保罗
    乔达默认值= America/Sao_Paulo
    JVM default = Europe/London
    Joda Default = America/Sao_Paulo
    true

    另请注意,t1 == t2返回true,这意味着它们是完全相同的实例。

    要改变JVM的默认设置后乔达的默认时区,则必须将其设置在DateTimeZone太:

    // 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 
    

    此输出:

    乔达默认设置为欧洲/伦敦

    重新启动一切后,缓存消失,Joda-Time获取新的d首次调用时默认。

    3

    你不应该直接使用乔达时间,但更好地利用丹尼尔·卢的库JodaTimeAndroid - 围绕乔达时间瘦包装),因为

    • 加载TZ数据时,它具有更好的性能特点on Android
    • 它有一个合适的广播接收器来跟踪system timezone的变化。
    相关问题