Java System.getProperty( “user.timezone” ) does not work

前端 未结 1 1169
误落风尘
误落风尘 2021-02-07 05:50

When I start java program by java -Duser.timezone=\"UTC\",

System.out.println( System.getProperty( \"user.timezone\" ) );
System.out.println( new D         


        
相关标签:
1条回答
  • 2021-02-07 05:55

    Your problem is that earlier, at JVM startup, Java has already set the default timezone, it has called TimeZone.setDefault(...); using the original "user.timezone" property. Just changing the property afterwards with System.setProperty("user.timezone", "UTC") has in itself no effect.

    That's why the normal way to set the default timezone at start time is: java -Duser.timezone=...

    If you insist on setting the timezone programatically, you can, after changing the property, set the default timezone to null to force its recalculation:

      System.setProperty("user.timezone", "UTC");
      TimeZone.setDefault(null);
    

    (from here).

    Or, simpler and cleaner, set it explicity:

    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    

    Be aware of potential issues if running under a SecurityManager.

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