Java System.getProperty("user.timezone") 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19121928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java System.getProperty( "user.timezone" ) does not work
提问by user1418717
When I start java program by java -Duser.timezone="UTC"
,
当我启动java程序时java -Duser.timezone="UTC"
,
System.out.println( System.getProperty( "user.timezone" ) );
System.out.println( new Date() ); // prints time in UTC
prints UTC time, but when I set in code like:
打印 UTC 时间,但是当我设置如下代码时:
System.setProperty( "user.timezone", "UTC" );
System.out.println( System.getProperty( "user.timezone" ) ); // prints 'UTC'
System.out.println( new Date() ); // prints time in local zone, not in UTC
does not print time in UTC . I need to set time in code. Not looking for Joda
不以 UTC 打印时间。我需要在代码中设置时间。不找乔达
Environment: JDK 1.6 / Windows XP
环境:JDK 1.6 / Windows XP
Please help. Thanks much!
请帮忙。非常感谢!
采纳答案by leonbloy
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.
您的问题是早些时候,在 JVM 启动时,Java 已经设置了默认时区,它TimeZone.setDefault(...);
使用原始"user.timezone"
属性进行了调用。之后只是更改属性System.setProperty("user.timezone", "UTC")
本身没有任何影响。
That's why the normal way to set the default timezone at start time is: java -Duser.timezone=...
这就是为什么在开始时间设置默认时区的正常方法是: 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:
如果您坚持以编程方式设置时区,则可以在更改属性后,将默认时区设置null
为强制重新计算:
System.setProperty("user.timezone", "UTC");
TimeZone.setDefault(null);
(from here).
(从这里)。
Or, simpler and cleaner, assign it directly with TimeZone.setDefault(...);
.
或者,更简单更简洁,直接用TimeZone.setDefault(...);
.