Java System.getProperty(“user.timezone”)不起作用 [英] Java System.getProperty( "user.timezone" ) does not work

查看:1761
本文介绍了Java System.getProperty(“user.timezone”)不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过 java -Duser.timezone =UTC启动java程序时,

  System.out.println(System.getProperty(user.timezone)); 
System.out.println(new Date()); //以UTC为单位打印时间

打印UTC时间,但是当我设置代码如下:

  System.setProperty(user.timezone,UTC); 
System.out.println(System.getProperty(user.timezone)); //打印'UTC'
System.out.println(new Date()); //打印本地区域的时间,而不是UTC

不会以UTC打印时间。我需要在代码中设置时间。不寻找Joda



环境:JDK 1.6 / Windows XP



请帮忙。非常感谢!

解决方案

您的问题是,早期,在JVM启动时,Java已经设置了默认的时区, code> TimeZone.setDefault(...); 使用原始的user.timezone属性。只需使用 System.setProperty(user.timezone,UTC)更改属性本身没有任何效果。



这就是为什么在开始时设置默认时区的正常方法是: java -Duser.timezone = ...



如果您坚持以编程方式设置时区,则可以在调用 System.setProperty(user.timezone)后)将默认时区设置为 null ,以强制重新计算:

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

(从这里)。或者,更简单和干净,直接使用 TimeZone.setDefault(...); 分配。


When I start java program by 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:

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

Environment: JDK 1.6 / Windows XP

Please help. Thanks much!

解决方案

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 calling System.setProperty( "user.timezone", ... ) set the default timezone to null, to force its recalculation:

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

(from here).

Or, more simple and clean, assign it directly with TimeZone.setDefault(...);.

这篇关于Java System.getProperty(“user.timezone”)不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆