不同服务器new Date的输出不同(GMT+800或者CST)

来源:互联网 发布:网络诈骗800元 编辑:程序博客网 时间:2024/06/03 22:47

问题描述:

不同的服务器上,java程序中通过打印new Date() 打印出的结果不同:
Fri Dec 05 17:14:55 GMT+08:00 2014

Fri Dec 05 17:15:55 CST 2014

这样因为我们后台数据库操作有一项时向数据库中插入一个date格式的数据,数据库中定义的是date类型,前台(flex)传递传递的也是date类型的,而数据库接受date类型的字符串只接受CST类型的,只有是CMT类型的就会出错。这样的话,我们实施的同志们部署好服务器后,导致某项功能不能使用。

解决方案:

1.在系统启动的时候改变系统的user.timezone属性为想要的值。我个人的做法是在程序中添加一个listener,系统一启动,就会调用该listener,通过这个类改变System.getProperty("user.timezone");的值。

代码如下:

System.setProperty("user.timezone", "GMT+08:00");
System.out.println(System.getProperty("user.timezone"));

怀着一颗赤诚之心,打开tomcat,运行程序,测试,结果还是失败。心情瞬间down到低谷。但是问题没有解决,现在放弃还太早。所以到网上狂搜,度娘还是不如谷歌。最终在谷歌上找到这么一段话,幡然醒悟:

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(...);.

意思就是在我们设置System.setProperty之前已经调用了TimeZone.setDefault()方法,这样在getDefault方法中就不在会调用System.getProperty()方法了。


通过上面谷歌搜索给出的解决方法,可以使问题得以解决:

最终listener中的代码如下:

System.setProperty("user.timezone", "GMT+08:00");
TimeZone.setDefault(null);
System.out.println(System.getProperty("user.timezone"));
2.通过修改注册表:

 HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Time Zones

修改方式

从正确的机器上拷贝一份注册表。

覆盖。之后但是还是没有成功。最重要的一步是,在操作系统中重新设置一次系统时区。

搞定

0 0
原创粉丝点击